在ComponentDidUpdate()中设置状态setState()进入无限循环?

时间:2019-12-07 20:46:49

标签: javascript reactjs

如果有人可以帮助我吗? 我需要此功能来将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
            })
        }
    }
}

1 个答案:

答案 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
      });
    }
  }
}