简体   繁体   中英

Dispatching redux actions within React componentDidUpdate

I am trying to dispatch a redux action in the componentDidUpdate lifecycle method, however it results in an infinite loop that causes the application to crash. Here's the code I currently have:

   componentDidUpdate(prevProps, prevState) {
    const { dispatch, sockOpen, user } = this.props;
    if (
      navigator.onLine &&
      user &&
      (sockOpen !== prevProps.sockOpen || sockOpen)
    ) {
      dispatch(pollStartAction());
      this._checkSessionIntervalId = setInterval(
        this.checkActiveSessions,
        5000
      );
    }
  }

Is this the right way of doing this or is there a better of writing this that wouldn't result in an infinite render loop. Thanks.

Presumably dispatching that action is updating the store, which is updating props, which triggers componentDidUpdate again. The usual way around this is to have some conditional that eventually stops the action from dispatching again, which it looks like you're trying to do, but that conditional is always evaluating to true. Without knowing what the parts of that conditional mean for sure, I'd guess that the problem is something with:

(sockOpen !== prevProps.sockOpen || sockOpen)

whenever sockOpen is truthy, the dispatch will run and you'll loop. Whenever sockOpen's value is different from the previous update, it will also loop. So, even if sockOpen is falsey, it will still loop if sockOpen was truthy last time. That means if sockOpen is ever truthy, the loop becomes infinite, since even if something happens to make sockOpen falsey, it was truthy on the last loop, and the first part of that or clause is true.

You need to figure out what the conditions are where that dispatch should NOT happen, set the terms of conditional to match those, and most importantly make sure it's possible for that set of conditions to occur!

Your logic is wrong. In (sockOpen !== prevProps.sockOpen || sockOpen) , once sockOpen is true, it will always run the pollStartAction() logic. If you want that to run once when it turns true, then you need it to be && sockOpen instead.

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