如果有人可以帮助我吗?
我需要此功能来将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
})
}
}
}
答案 0 :(得分:0)
在componentDidUpdate
中设置状态时需要非常小心。调用setState
将更新组件,从而触发componentDidUpdate
,并调用setState
,依此类推,从而导致无限循环。从React docs:
您可以在
setState()
中立即调用componentDidUpdate()
,但请注意,它必须包裹在一个条件中...否则会导致无限循环。
解决方案是添加某种条件,以免不必要地更新状态。例如:
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
});
}
}
}