Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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())
      }
    }
See Question&Answers more detail:os

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...