react生命周期

281 阅读2分钟

挂载

  1. ** constructor(props) **
    用途:
  • 通过给 this.state 赋值对象来初始化内部 state。
  • 为事件处理函数绑定实例
  1. ** static getDerivedStateFromProps(props, state) **
    调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。

  2. ** render() **

  3. ** componentDidMount() **
    组件挂载后(插入 DOM 树中)
    用途:

  • 依赖于DOM的操作
  • 通过网络请求获取数据
  • 订阅

即将过时,避免使用:
UNSAFE_componentWillMount()
服务端渲染唯一会执行到的生命周期

更新

getDerivedStateFromProps()

  1. ** shouldComponentUpdate(nextProps, nextState) **
    返回false,则不继续执行以下的生命周期。但不会阻止子组件在 state 更改时重新渲染。
    用途:
  • 优化,减少不必要的渲染

render()

  1. ** getSnapshotBeforeUpdate(prevProps, prevState) **
    返回值作为componentDidUpdate的第三个参数
    用途:
  • UI处理
  1. ** componentDidUpdate(prevProps, prevState, snapshot) **
    更新后
    用途:
  • 操作DOM
  • 比较props或state是否更新去做网络请求

即将过时,避免使用:
UNSAFE_componentWillUpdate(nextProps, nextState)
当组件收到新的 props 或 state 时,会在渲染之前调用 UNSAFE_componentWillReceiveProps(nextProps)
已挂载的组件接收新的 props 之前被调用

卸载

  1. ** componentWillUnmount() **
    组件卸载及销毁之前
    用途:
  • 清理(定时器、事件绑定等)

错误处理

  1. ** static getDerivedStateFromError(error) **
    会在后代组件抛出错误后被调用,返回值更新state

  2. ** componentDidCatch(error, info) **

父子初始化(父P子C)

-》 P constructor
-》 P static getDerivedStateFromProps
-》 P render
-》 C constructor
-》 C static getDerivedStateFromProps
-》 C render
-》 C componentDidMount
-》 P componentDidMount

父组件修改state不传递到子组件

-》 P static getDerivedStateFromProps
-》 P shouldComponentUpdate
-》 P render
-》 C static getDerivedStateFromProps
-》 C shouldComponentUpdate
-》 C render
-》 C getSnapshotBeforeUpdate
-》 P getSnapshotBeforeUpdate
-》 C componentDidUpdate
-》 P componentDidUpdate
** 注意:父组件修改的值不影响子组件,子组件也会触发更新的生命周期 **

父组件修改state传递到子组件的props

-》 P static getDerivedStateFromProps
-》 P shouldComponentUpdate
-》 P render
-》 C static getDerivedStateFromProps
-》 C shouldComponentUpdate
-》 C render
-》 C getSnapshotBeforeUpdate
-》 P getSnapshotBeforeUpdate
-》 C componentDidUpdate
-》 P componentDidUpdate

子组件修改state

-》C static getDerivedStateFromProps
-》C shouldComponentUpdate
-》C render
-》C getSnapshotBeforeUpdate
-》C componentDidUpdate