react: 生命周期

1. 旧版本的声明周期

1. 原理解析

初始化阶段: 由ReactDOM.render()触发初次渲染

  1. constructor()
  2. componentWillMount()
  3. render()
  4. componentDidMount() =====> 常用

更新阶段,由组件内部this.setSate()或父组件render触发

  1. componentWillReceiveProps(),父组件第一次render不触发,第二次及之后render()时才会触发
  2. shouldComponentUpdate()
  3. componentWillUpdate()
  4. render() =====> 必须使用的一个
  5. componentDidUpdate()
  6. 若执行shouldComponentUpdate方法返回true时可以正常继续下面的流程
  7. 若shouldComponentUpdate方法返回false时则返回,不执行后面的流程
  8. 强制更新时会跳过shouldComponentUpdate()

卸载阶段,由ReactDOM.unmountComponentAtNode()触发

  1. componentWillUnmount() =====> 常用

2. 原理图

2. 新版本声明周期

删除了componentWillMount(),componentWillReceiveProps(), componentWillUpdate()

1. getDerivedStateFromProps

  • 必须用static修饰
  • 若state的值在任何时候都取决于props,那么可以使用getDerivedStateFromProps
  • 接收两个参数,props和state
  • 若返回值不为null,则将返回值和state进行合并

2. getSnapshotBeforeUpdate

  • 该方法的返回值作为参数传递给componentDidUpdate,即下面的snapshotValue
  • componentDidUpdate(preProps,preState,snapshotValue)

3. 原理解析

初始化阶段: 由ReactDOM.render()触发初次渲染

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount() =====> 常用

更新阶段,由组件内部this.setSate()或父组件render触发

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render() =====> 必须使用的一个
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()
  6. 若执行shouldComponentUpdate方法返回true时可以正常继续下面的流程
  7. 若shouldComponentUpdate方法返回false时则返回,不执行后面的流程
  8. 强制更新时会跳过shouldComponentUpdate()

卸载阶段,由ReactDOM.unmountComponentAtNode()触发

  1. componentWillUnmount() =====> 常用

2. 原理图

如果文章对您有所帮助,可以点一下推荐哦
原文地址:https://www.cnblogs.com/virgosnail/p/15635886.html