React 较难理解的生命周期钩子函数

2022-10-28 14:28:58
1.   constructor

在react中,class 里的constructor 方法 用来初始化state和绑定事件方法
其中,super作为方法执行父类的构造函数,参数为props 即接受父组件传入的props

如果没有执行super, react会报错

  1. componentWillReceiveProps(nextProps)

执行时间:当一个已mount的react组件接收到新的props的时候会自动调用该钩子
参数:nextProps

注意:
即使props没有改变,该方法也可能会被调用,因此需要将新旧props值进行对比然后操作
在组件mounting阶段,该方法不会被掉起,setState 也不会触发该方法

// 更新子组件中的state,当查询参数变化的时候
componentWillReceiveProps(nextProps) {if (JSON.stringify(nextProps.query) !==JSON.stringify(this.props.query)) {this.setState({
        hasmore:true,
        loading:false,
        count:0,
        page: nextProps.page,
      }, () => {this.listener();this.autoLoad(nextProps);
      });
    }
  1. shouldComponentUpdate (nextProps,nextState)

执行时间:当的判断state或者props 的变化 是否影响组件的output的时候
返回true 表示不影响,即组件正常执行render方法
返回false 表示影响, 即组件不执行render方法,但返回false不会阻止子组件在其状态更改时重新呈现
注意:
返回false 会阻止 componentWillUpdate,render,componentDidUpdate 的调用,未来react可能会削弱这种强阻止的行为,该用提示的形式。

初始化render的时候或者执行forceUpdate的时候,不会执行该方法。

 shouldComponentUpdate(nextProps, nextState) {if (this.props.children === nextProps.children) {returnfalse;
    }returntrue;
  }
  1. componentWillUnmount()

执行时间:当component被unmounted 和destroyed 的时候

在这个钩子函数内部 可以取消 componentDidMount方法中定义的 定时器,网络请求,以及DOM元素

  • 作者:Vin1992
  • 原文链接:https://blog.csdn.net/Vin1992/article/details/78096437
    更新时间:2022-10-28 14:28:58