![](/img/trans.png)
[英]React setState inside componentDidUpdate causing infinite loop
[英]Setting state setState() inside ComponentDidUpdate() going to infinite loop?
如果有人可以幫助我嗎? 我需要這個函數來存儲狀態中的filteredObject
鍵。 但是當我在componentDidMount()
調用這個函數時,它沒有工作,當我在ComponentDidUpdate()
調用它時,它工作但進入無限循環?
userData = () => {
const returnedEmail = storageManger.getEmailFromStore();
const { agents } = this.state;
if (returnedEmail) {
const filteredEmail = agents.find(agent => { return agent.email === returnedEmail })
if (filteredEmail) {
this.setState({
agentApplicationId: filteredEmail.properties
})
}
}
}
在componentDidUpdate
設置狀態時需要非常小心。 調用setState
更新組件,觸發componentDidUpdate
,調用setState
等等,導致無限循環。 來自React 文檔:
您可以在
componentDidUpdate()
setState()
立即調用setState()
但請注意它必須包含在條件中...否則會導致無限循環。
解決方案是添加某種條件,這樣您就不會不必要地更新狀態。 例如:
userData = () => {
const returnedEmail = storageManger.getEmailFromStore();
const { agents, agentApplicationId } = this.state;
if (returnedEmail) {
const filteredEmail = agents.find(agent => agent.email === returnedEmail);
// Add an extra condition here to prevent state from updating if the values are already equal.
if (filteredEmail && filteredEmail.properties !== agentApplicationId) {
this.setState({
agentApplicationId: filteredEmail.properties
});
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.