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