React 상태에 문제가 있습니다. 그것은 객체 배열을받으며 상태가 올바르게 설정되어 있지만 함수가 끝나면 상태가 비어 있음을 나타냅니다. 아무도이 동작을 설명 할 수 있습니까?API 요청 후 ReactJS 상태가 업데이트됩니다.
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) [{…}, {…}, {…}, {…}, {…}]
이러한 질문은 getWeather() 함수는 잘 작동 및 상태를 설정하는 것을 언급하는 것을 잊었다. – bordax