Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - componentDidUpdate vs componentWillReceiveProps use case in react

This is how we use componentWillReceiveProps

componentWillReceiveProps(nextProps) {
  if(nextProps.myProp !== this.props.myProps) {
    // nextProps.myProp has a different value than our current prop
  }
}

It's very similar to componentDidUpdate

componentDidUpdate(prevProps) {
  if(prevProps.myProps !== this.props.myProp) {
    // this.props.myProp has a different value
    // ...
  }
}

I can see some differences, like if I do setState in componentDidUpdate, render will trigger twice, and the argument for componentWillReceiveProps is nextProps, while argument for componentDidUpdate is prevProp, but seriously I don't know when to use them. I often use componentDidUpdate, but with prevState, like change a dropdown state and call api

eg.

componentDidUpdate(prevProps, prevState) {
      if(prevState.seleted !== this.state.seleted) {
        this.setState({ selected: something}, ()=> callAPI())
      }
    }
question from:https://stackoverflow.com/questions/49386324/componentdidupdate-vs-componentwillreceiveprops-use-case-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The main difference between the two is:

  • When they are called in a component's lifecycle
  • How it updates component state

When are they called?

As the names suggest – and as you probably know since you mentioned "if I do setState in componentDidUpdate, render will trigger twice" – componentDidUpdate is called after the component updates (received new props or state). This is why the parameters to this function is prevProps and prevState.

So if you wanted to do something before the component received new props, you'd use componentWillReceiveProps, and if you wanted to do something after it received new props or state, you'd use componentDidUpdate.

How do they update state?

The main difference here is:

This can be important as there are some gotchya's that can come up when trying to sync state with other parts of your component's props.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...