我在下面有一个函数,它设置一个 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>
)
}
});
最佳答案
初始状态没有数据
。将您的代码更改为-
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 响应包含城市、天气等对象......
关于javascript - reactjs render() 在 promise 解决后未触发 this.setState 被重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39956925/