componentWillReceiveProps & componentDidUpdate

componentWillReceiveProps(nextProps) {
    
    
    if(nextProps.count !== this.props.count) 
         // doSomething
    }
}
componentDidUpdate(prevProps) {
    
    
    if(prevProps.count !==  this.props.count) {
    
    
        this.setState({
    
    
            count: this.props.count
        })
    } 
}

When to call in the React lifecycle

componentWillReceiveProps is triggered before the component accepts new props, and
componentDidUpdate is triggered after the component accepts new props

If you want to do something before the component receives new props, you can use componentWillReceiveProps, if you want to do something after receiving new props or status, you can use componentDidUpdate

Ways to update state

The update status of
componentWillReceiveProps is synchronous. The update status of componentDidUpdate is asynchronous.
This difference is very important, and it is also an important reason for the obsolete life cycle of componentWillReceiveProps (which may cause some problems), so it is recommended to use componentDidUpdate

Guess you like

Origin blog.csdn.net/Slueia/article/details/113780896