复习React生命周期

154 阅读2分钟

image.png

初始化挂载阶段

  • ! getDefaultProps:获取实例的默认属性 (只支持 React.createClass 创建的组件)

  • ! getInitialState:获取每个实例的初始化状态 (只支持 React.createClass 创建的组件)

  • constructor 函数中不要调用 setState() 方法。如果你的组件需要使用内部 state,请直接在构造函数中为 this.state 赋值初始 state

    • 通过给 this.state 赋值对象来初始化内部 state
    • 为事件处理函数绑定实例
    constructor(props) {
      super(props);
      // 不要在这里调用 this.setState()
      this.state = { counter: 0 };
      this.handleClick = this.handleClick.bind(this);
    }
    
  • ! componentWillMount:在组件挂载之前被调用。它在 render() 之前调用,因此在此方法中同步调用 setState() 不会触发额外渲染,在新版本中使用建议使用 UNSAFE_componentWillMount 代替

  • render:组件在这里根据元素的类型生成虚拟DOM节点

  • componentDidMount:会在组件挂载后(插入 DOM 树中)立即调用。依赖于 DOM 节点的初始化应该放在这里。如需通过网络请求获取数据,此处是实例化请求的好地方

运行中状态: 当组件的props 或者state 更新之后

  • componentWillReceiveProps(nextProps): 会在已挂载的组件接收新的 props 之前被调用,如果你需要更新状态以响应 props 更改(例如,重置它),你可以比较 this.propsnextProps 并在此方法中使用 this.setState() 执行 state 转换 UNSAFE_componentWillReceiveProps()

  • shouldComponentUpdate(): 组件接受到新属性或者新状态的时候(可以返回 false,接收数据后不更新,阻止 render 调用,后面的函数不会被继续执行了)此方法仅作为性能优化的方式而存在。不要企图依靠此方法来“阻止”渲染,因为这可能会产生 bug。,PureComponent 会对 props 和 state 进行浅层比较,并减少了跳过必要更新的可能性。

  • ! componentWillUpdate(nextProps, nextState) : 当组件收到新的 props 或 state 时会在渲染之前调用此方法,使用此作为在更新发生之前执行准备更新的机会。初始渲染不会调用此方法。不能此方法中调用 this.setState();在 componentWillUpdate() 返回之前,也不应该执行任何其他操作(例如,dispatch Redux 的 action)触发对 React 组件的更新,此方法以过时 UNSAFE_componentWillUpdate()

  • render:组件渲染组件

  • getSnapshotBeforeUpdate(prevProps, prevState) , getSnapshotBeforeUpdate() 在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期的任何返回值将作为参数传递给 componentDidUpdate()

  • componentDidUpdate(prevProps, prevState, snapshot): 组件已经更新 会在更新后会被立即调用。首次渲染不会执行此方法。

销毁阶段:

  • componentWillUnmount:组件即将销毁 会在组件卸载及销毁之前直接调用。在此方法中执行必要的清理操作,例如,清除 timer,取消网络请求或清除在 componentDidMount() 中创建的订阅等。