我遇到了React状态的问题。它接收一个对象数组,并在状态下正确设置,但随后函数结束,表明状态为空。任何人都可以解释这种行为吗?
componentDidMount() {
this.getWeather();
this.getForecast();
this.setState({location: ''});
}
getWeather() {
if (this.state.location === "") {
this.setState({error: 'Please enter something'});
} else {
OpenWeather.getWeather(this.state.location).then(result => {
if (result.cod === "404") {
this.setState({error: 'City not found'});
} else if (result.cod === 200) {
this.setState({error: ''});
this.setState({weather: result});
} else {
this.setState({error: 'Server error'});
}
});
}
}
getForecast() {
OpenWeather.getForecast(this.state.location).then(forecast => {
console.log("Returned forecast:");
console.log(forecast);
this.setState({forecast: forecast});
console.log("Forecast saved to state(inside function)");
console.log(this.state.forecast);
});
console.log("Forecast saved to state(outside function)");
console.log(this.state.forecast);
}
控制台输出:
Forecast saved to state(outside function)
[]
Returned forecast:
(5) [{…}, {…}, {…}, {…}, {…}]
Forecast saved to state(inside function)
(5) [{…}, {…}, {…}, {…}, {…}]
答案 0 :(得分:3)
有两件事,从概念上讲是错误的。
首先:您对OpenWeather. getForecast
的API请求是异步的,因此在您的API返回响应之前,Javascript代码在执行之后会因此而得到第一个响应
Forecast saved to state(outside function)
[]
现在,当Api成功时,你得到了
Returned forecast:
(5) [{…}, {…}, {…}, {…}, {…}]
第二:由于setState是异步的,因此您的第三个语句
console.log("Forecast saved to state(inside function)");
console.log(this.state.forecast);
可能会也可能不会为您提供更新后的价值。您应该使用setState回调。
检查这些问题以获取更多信息