react 生命周期

  • 初始化

    • constructor

      • 定义state 初始状态
      • 用户不使用state的话,纯用props接受参数,有没有constructor都可以,可以不用constructor。
      • 关于 constructor 中的 super() 和 super(props)
        • http://es6.ruanyifeng.com/#docs/class-extends
        • 在constructor中使用this.props的时候,super需要加入(props) super中的props是否接收,只能影响constructor生命周期能否使用this.props,其他的生命周期已默认存在this.props
    • componentWillMount

      • 将要装载
      • 可以在服务端被调用,也可以在浏览器端被调用
      • 使用这个钩子会给出警告 componentWillMount → UNSAFE_componentWillMount 对于每种 unsafe 的方法,通常有更好的解决方案。
      • 暂时没什么使用的场景 以后用到在补充吧 可能就废弃了
    • render

      • 不能在render函数中调用setState。会进入死循环
    • componentDidMount

      • 装载完成
      • 只能在浏览器端被调用,在服务器端使用react的时候不会被调用
      • 异步的一些发法放在这里处理比较合适
  • state更新

    • shouldComponentUpdate
    • componentWillUpdate
      • 不能在该函数中通过this.setstate再次改变state,如果需要,则在shouldComponentUpdate函数中改变
    • render
    • componentDidUpdate
  • props更新

    • componentWillReceiveProps(nextProps)
      • 使用场景:过props属性更新state的值 是在render之前更新,这次更新不会触发新的渲染
      • 区别: 无论返回什么,true还是false, 都会往下执行shouldComponentUpdate
    • shouldComponentUpdate(nextProps, nextState)
      • 阻止不必要的渲染 优化性能
      • 区别: 如果返回true, 则会继续执行render; 如果返回false, 则不会继续执行render
    • componentWillUpdate
      • 一般不用
    • render
    • componentDidUpdate
      • 一般不用 在前两个周期周就可以满足 基本需求了 再次操作state造成循环
  • 强制更新

    • 当强制刷新的组件为子组件时
      • 场景
        • 有些变量不在state上,当时你又想达到这个变量更新的时候,触发render
        • state里的某个变量层次太深,更新的时候没有自动触发render。这些时候都可以手动调用forceUpdate自动触发render
      • componentWillUpdate
      • render
      • componentDidUpdate
    • 当强制刷新的组件中含有子组件时 会触发子组件的更新
      • 场景
        • 包含子组件的组最好不要用这个更新 会造成很多没必要的渲染 解决方式千千种
      • 父componentWillUpdate
      • 父render
      • 子componentWillReceiveProps
      • 子shouldComponentUpdate
      • 子componentWillUpdate
      • 子render
      • 子componentDidUpdate
      • 父componentDidUpdate
  • 组件卸载

    • ReactDOM.unmountComponentAtNode(container);
      • 注意:其中的子组件都会被卸载
原文地址:https://www.cnblogs.com/chen-yi-yi/p/13542476.html