简体   繁体   中英

Setting state setState() inside ComponentDidUpdate() going to infinite loop?

If someone can help me with this ? I need this function to store the filteredObject key in the state. but when I call this function in componentDidMount() , it didn't work and when I called it in ComponentDidUpdate() it works but going on a infinite loop?

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
            })
        }
    }
}

You need to be very careful when setting state in componentDidUpdate . Calling setState updates the component, which triggers componentDidUpdate , which calls setState , and so on, causing the infinite loop. From the React docs :

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition...or you'll cause an infinite loop.

The solution is to add some kind of condition so you're not updating state unnecessarily. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM