简体   繁体   中英

Mutating state in shouldComponentUpdate react 16.6.3

Since react have deprecated many of their Lifecycle Methods I found that, when using redux and connect when I want to augment local state of a component I am using componentDidUpdate . The problem is only prevProps, prevState are passed to this function.

That then means I only have nextProps, nextState inside the shouldComponentUpdate lifeCycle`.

To me this feels inherently wrong to do something as follows:

  shouldComponentUpdate(nextProps) {
    const { status_status } = nextProps;
    if(status_status === "error") {
      this.props.dispatch(resetStatus());
    }
    return true;
  }

This is surely an antiPattern and I should not be doing this.

How can I then get the nextProps without using shouldComponentUpdate

I was having similar case and I had found getDerivedStateFromProps useful and suitable in such condition.

static getDerivedStateFromProps(props, state) {
  // now, you may dispatch checking the condition
  // BTW, you will dispatch just using props
  // props.dispatch()
  // this.props.dispatch() // invalid
}

I know this note from the docs :

If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

But I am just sharing my experience that was only the case getDerivedStateFromProps working.

However, I would also suggest you to use componentDidUpdate hook first. And if everything seems good for you, then stick with it. Or if you also face using componentDidUpdate and feel alright using getDerivedStateFromProps then you may post your opinion and ideas as an answer.

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