Reactjs的render()在promise解决这个问题后不会被触发.setState被重新分配

reactjs render() not triggered after promise resolves this.setState is re-assigned

本文关键字:setState 新分配 分配 问题 render promise 解决 Reactjs      更新时间:2023-09-26

下面有一个函数,它设置了一个InitialState,然后使用componentWillMount和fetchData调用api,为数据分配this.state。然而,当this. setstate()完成后,渲染函数不会被新的this触发。状态数据我的函数如下:

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>
    )
  }
});

初始状态无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响应包含对象作为城市,天气,…等等. .

根据react文档

componentWillMountclient and server上调用一次,在初始呈现发生之前立即调用。如果在这个方法中调用setState, render()将看到更新的状态,并且尽管状态发生了变化,但只执行once

要解决此问题,请使用componentDidMount代替componentWillMount。由于您正在更新状态变量data中的响应,因此首先定义它,然后无需定义其他状态变量,只需将数据传递给child component并更新状态,就像您现在所做的那样。

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