【发布时间】:2017-02-18 19:05:25
【问题描述】:
我有一个函数,它在下面设置一个 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 和 render 中插入了一个 console.log,promise 解决了,setState 被执行,但是 render 方法不会重新运行并使用新的 this.state 值更新
-
那么,答案应该对您有所帮助。
componentWillMount很少使用。
标签: javascript reactjs components render setstate