componentDidUpdate vs componentWillReceiveProps use case in react

前端 未结 1 1275
清酒与你
清酒与你 2020-12-24 11:44

This is how we use componentWillReceiveProps

componentWillReceiveProps(nextProps) {
  if(nextProps.myProp !== this.props.myProps) {
    // nextP         


        
相关标签:
1条回答
  • 2020-12-24 11:57

    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:

    • componentWillReceiveProps will update state synchronously
    • componentDidUpdate will update state asynchronously.

    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.

    0 讨论(0)
提交回复
热议问题