[英]reactjs render() not triggered after promise resolves this.setState is re-assigned
我在下面有一個函數,它設置一個 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>
)
}
});
沒有關於初始狀態的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 響應包含城市、天氣等對象。
根據反應文檔
componentWillMount
在初始渲染發生之前立即在client and server
上被調用一次。 如果您在此方法中調用 setState, render()
將看到更新的狀態,並且盡管狀態發生變化也只會執行once
。
為了解決這個問題,而不是componentWillMount
使用componentDidMount
。 由於您正在更新狀態變量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>
)
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.