react 性能优化之 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
        })
    } 
}
区别:
生命周期调用时机不同
componentWillReceiveProps在组件接受新的props之前触发,
componentDidUpdate在组件接受新的props之后触发

更新state的方式

最主要的区别是

  • componentWillReceiveProps更新状态是同步的
  • componentDidUpdate更新状态是异步的
    这点区别非常重要,也是componentWillReceiveProps生命周期被废弃的重要原因(可能导致某些问题), 所以推荐使用componentDidUpdate
转载链接:https://www.jianshu.com/p/638f67160fcf

 
原文地址:https://www.cnblogs.com/xiaoyaoweb/p/12881892.html