React生命周期

前言

在React中组件的生命周期会经历三个过程:

  • 挂载(Mount),第一次在DOM树渲染
  • 更新(Update),组件被重新渲染
  • 卸载(Unmount),组件在DOM树中删除

这里是不同阶段生命周期执行顺序:
React 生命周期流程简介(1)

初始化:

在组件初始化阶段会执行

  1. constructor
  2. static getDerivedStateFromProps()
  3. componentWillMount() / UNSAFE_componentWillMount()
  4. render()
  5. componentDidMount()

更新阶段:

propsstate的改变可能会引起组件的更新,组件重新渲染的过程中会调用以下方法:

  1. componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()
  2. static getDerivedStateFromProps()
  3. shouldComponentUpdate()
  4. componentWillUpdate() / UNSAFE_componentWillUpdate()
  5. render()
  6. getSnapshotBeforeUpdate()
  7. componentDidUpdate()

卸载阶段:

  1. componentWillUnmount()

在react中生命周期一共有这样几个:

1、组件将要挂载时触发:componentWillMount
2、组件挂载完成时触发:componentDidMount
3、是否要更新数据时触发:shouldComponentUpdate
4、将要更新数据时触发:componentWillUpdate
5、数据更新完成时触发:componentDidUpdate
6、组件将要销毁时触发:componentWillUnmount
7、父组件中改变了props传值时触发:componentWillReceiveProps
8、错误处理:componentDidCatch()

因为有些钩子是要被废弃的,所以在书写时必须在前面加UNSAFE_才不会有这样的警告,比如:UNSAFE_componentWillMount

React 生命周期流程简介(1)
React 生命周期流程简介(1)



在v16.4中不同阶段生命周期执行是这样的:

React 生命周期流程简介(1)


react 12个生命周期函数,各个函数的细节详解可看这篇文章:

https://blog.csdn.net/g1437353759/article/details/109014040

相关文章:

  • 2021-10-05
  • 2021-04-20
  • 2021-12-10
  • 2021-12-04
  • 2021-10-15
  • 2021-04-17
  • 2021-06-08
猜你喜欢
  • 2022-02-19
  • 2022-12-23
  • 2021-10-17
  • 2021-05-28
  • 2022-01-19
  • 2021-08-30
  • 2021-04-14
相关资源
相似解决方案