2017-12-29 25 views
2

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) [{…}, {…}, {…}, {…}, {…}] 
+0

のためにこれらの質問はgetWeather()関数が正常に動作し、状態を設定することを言及するのを忘れてしまいました。 – bordax

答えて

3

二つのことは、概念的には間違っています。

まず:OpenWeather. getForecastへのあなたのAPIリクエストは非同期であるので、それが実行されているので、あなたが今

Forecast saved to state(outside function) 
[] 

として最初の応答を取得した後、あなたのAPIは、応答Javascriptコードを返す前にするときのAPIの結果で成功、あなたは

Returned forecast: 
(5) [{…}, {…}, {…}, {…}, {…}] 

セカンド取得:SETSTATEが非同期であるので、あなたの第三の文

console.log("Forecast saved to state(inside function)"); 
console.log(this.state.forecast); 

更新された値が表示される場合とされない場合があります。代わりに、setStateコールバックを使用する必要があります。

チェック詳細

When to use React setState callback

calling setState doesn't mutate state immediately

+0

ok。追加された非同期は、ほぼすべての私のComponentメソッドを待っています。現在、両方の関数の実行が終了した後に状態が設定されていますが、レンダリングメソッドではまだ状態値にアクセスできません。 – bordax

+0

あなたはどのようにエラーが発生しましたか?状態として –

+0

にアクセスしようとしていますが、これはリストとして保存されています。this.state.forecast [0] .mainによってアクセスしようとしています。私は正常な応答を得る。 console.logをconponentWillMountの最後に追加して、正しいresusltsを出力しました – bordax

関連する問題