2

以下に、InitialState を設定し、componentWillMount と fetchData を使用して API 呼び出しを行い、データ this.state を割り当てる関数があります。ただし、 this.setState() が完了すると、レンダー関数は新しい this.state データでトリガーされません。私の関数は以下のとおりです。

var Home = React.createClass({
  getInitialState: function() {
    return {
      city: '',
      weather: '',
      temperature: 0,
      humidity: 0,
      wind: 0,
    }
  },
  fetchData: function() {
    apiHelpers.getCityInfo()
    .then(function (response){
      this.setState({ data: response
      })
    }.bind(this))
  },
  componentWillMount: function(){
    this.fetchData();
  },
  render: function () {
    return (
      <div className="container">
      <Cities data={this.state.data} />
      </div>
    )
  }
});
4

2 に答える 2

1

data初期状態ではありません。コードを次のように変更します-

fetchData: function() {
    apiHelpers.getCityInfo()
     .then(function (response){
      this.setState({
          city: response.city,
          weather: response.weather,
          temperature: response.temperature,
          humidity: response.humidity,
          wind: response.wind,
       })
    }.bind(this))
  },

あなたのAPI応答が都市、天気などのオブジェクトを含むことを期待しています..

于 2016-10-10T11:32:46.763 に答える