Reactjs API请求无限。为什么?
我创建天气应用程序并使用API openweathermap。 我从API获取数据,但控制台中的网络显示无限请求 我的反应码Reactjs API请求无限。为什么?,reactjs,api,request,fetch,Reactjs,Api,Request,Fetch,我创建天气应用程序并使用API openweathermap。 我从API获取数据,但控制台中的网络显示无限请求 我的反应码 class CityWeather extends Component { constructor(props){ super(props) this.state = { city: "", temp: "", date: "Today" } } render() { const fetch
class CityWeather extends Component {
constructor(props){
super(props)
this.state = {
city: "",
temp: "",
date: "Today"
}
}
render() {
const fetchWeatherData = location => {
const url = 'http://api.openweathermap.org/data/2.5/forecast?q='+location+'&units=metric&APPID=65ea63d33ba78059603a85cba8c80620';
fetch(url).then(res =>
res.json()
).then(data => {
this.setState({
city: data.city.name,
temp: data.list[0].main.temp
})
})
}
return (
<div>
{fetchWeatherData(this.props.name)}
<div>{this.state.city}</div>
<div>{this.state.date}</div>
<div>{this.state.temp}</div>
</div>
)
}
}
class CityWeather扩展组件{
建造师(道具){
超级(道具)
此.state={
城市:“,
温度:“,
日期:“今天”
}
}
render(){
const fetchWeatherData=位置=>{
常量url=http://api.openweathermap.org/data/2.5/forecast?q=“+位置+”和单位=公制和APPID=65ea63d33ba78059603a85cba8c80620”;
获取(url)。然后(res=>
res.json()
)。然后(数据=>{
这是我的国家({
城市:data.city.name,
temp:data.list[0]。main.temp
})
})
}
返回(
{fetchWeatherData(this.props.name)}
{本州市}
{this.state.date}
{this.state.temp}
)
}
}
每次渲染时都会获取天气数据。当得到响应时,通过更改组件的状态,这会导致重新渲染,从而导致无限循环
也请看这篇文章:
相反,您应该在安装组件时获取天气数据,这只会发生一次。请参阅文档中的
class CityWeather扩展组件{
建造师(道具){
超级(道具)
此.state={
城市:“,
温度:“,
日期:“今天”
}
}
componentDidMount(){
const fetchWeatherData=位置=>{
常量url=http://api.openweathermap.org/data/2.5/forecast?q=“+位置+”和单位=公制和APPID=65ea63d33ba78059603a85cba8c80620”;
获取(url)
.then(res=>res.json())
。然后(数据=>{
这是我的国家({
城市:data.city.name,
temp:data.list[0]。main.temp
})
})
};
fetchWeatherData(this.props.name);
}
render(){
返回(
{本州市}
{this.state.date}
{this.state.temp}
)
}
}
每次渲染时都会获取天气数据。当得到响应时,通过更改组件的状态,这会导致重新渲染,从而导致无限循环
也请看这篇文章:
相反,您应该在安装组件时获取天气数据,这只会发生一次。请参阅文档中的
class CityWeather扩展组件{
建造师(道具){
超级(道具)
此.state={
城市:“,
温度:“,
日期:“今天”
}
}
componentDidMount(){
const fetchWeatherData=位置=>{
常量url=http://api.openweathermap.org/data/2.5/forecast?q=“+位置+”和单位=公制和APPID=65ea63d33ba78059603a85cba8c80620”;
获取(url)
.then(res=>res.json())
。然后(数据=>{
这是我的国家({
城市:data.city.name,
temp:data.list[0]。main.temp
})
})
};
fetchWeatherData(this.props.name);
}
render(){
返回(
{本州市}
{this.state.date}
{this.state.temp}
)
}
}