我正在製作一個非常簡單的React組件,它顯示從遠程源獲取的數據。獲取數據之前,它必須等待用戶在正確登錄這裏是我正在試圖做到這一點:如何從`componentDidUpdate`內部調用`dispatch`而不會以無限循環結束?
class MyComponent extends React.Component {
componentDidUpdate() {
if (this.props.loggedIn) {
api.getData()
.then(() => {
this.props.dispatch({
type: 'gotData'
})
}, (reason) => {
this.props.dispatch({
type: 'getDataFailed'
})
})
}
}
}
在我自己的話,每一次相關與這個國家的一部分組件(在這種情況下,loggedIn
道具)進行更新,componentDidUpdate
叫,我可以得到的數據,如果我看到在用戶登錄
這實際上工作得非常好,但有一個主要問題:似乎呼籲dispatch
最終再次觸發componentDidUpdate
,所以我最終在一個無限循環。我甚至不必在任何地方監聽這些調度事件,使用dispatch
函數的簡單事實足以再次觸發componentDidUpdate
。
我的猜測是調度執行我的根減速器,它在內部使用setState
,從而再次觸發整個生命週期鏈。
這種事情通常是怎麼完成的?如何在componentDidUpdate
之內撥打dispatch
而不結束無限循環?
我會考慮使用帶有componentWillReceieveProps()的子組件。將狀態作爲道具傳遞給該組件 –