React 学习笔记:React 生命周期

1,358 阅读2分钟

本文基于React 生命周期示意图整理,并不包含所有声明周期,要了解所有生命周期请看React 组件

基本概念

生命周期对应页面的 3 个加载过程

  1. 第一次加载过程

  2. props,state 和 父组件重新渲染导致的更新过程

  3. 离开页面,卸载过程

每个过程都有 3 个渲染阶段

  1. 渲染阶段,都是纯函数,可能被 react 暂停、终止或重新启动。

  2. 预提交阶段,预提交阶段能读取之前的 DOM, 这个阶段完成后 react 会更新 DOM 和 ref。

  3. 提交阶段,可以使用 DOM,运行副作用。

按照加载过程分类生命周期

加载过程

  1. constructor
  2. getDerivedStateFromProps
  3. render
  4. componentDidMount

更新过程

  1. getDerivedStateFromProps
  2. shouldComponentUpdate
  3. render
  4. getSnapShotBeforeUpdate
  5. componentDidUpdate

卸载过程

  1. componentWillUnmount

按照渲染阶段介绍生命周期

渲染阶段

getDerivedStateFromProps

static getDerivedStateFromProps(props, state)

调用时机:组件第一次加载或更新时调用。

使用:比较 props(新 props) 和 state(旧 props), 更新 state, 方便在 componentDidUpdate 更新副作用

用于结合 componentDidUpdate 更新副作用。

shouldComponentUpdate(nextProps, nextState)

调用时机:getDerivedStateFromProps 之后 render 之前调用。

使用:比较 props 和 nextProps,返回 false 组件不调用 render,返回 true, 组件仍然调用 render,

用于避免不必要的渲染,性能优化。

预提交阶段

getSnapshotBeforeUpdate

getSnapshotBeforeUpdate(prevProps, prevState)

调用时机:render 之后更新 DOM 和 ref 之前调用。

使用:获取渲染前的 DOM,返回值作为 componentDidUpdate 第三个参数,没有值应该返回 null

主要用法,需要对比渲染前后 DOM 变化时使用。

提交阶段

componentDidMount

componentDidMount()

调用时机:在组件第一次更新 DOM 和 ref 后调用。

主要用法,在组件第一次加载完成后调用,用于创建定时器,订阅,操作 DOM, 更新副作用。

componentDidUpdate

componentDidUpdate(prevProps, prevState, snapshot)

调用时机:在组件每次更新 DOM 和 ref 后调用。

主要用法:用于操作 DOM,更新副作用。

componentWillUnmount

componentWillUnmount()

调用时机:组件卸载或销毁前执行,销毁是指组件销毁重新创建。

主要用法:用于取消订阅,取消定时器。

参考文章

1,React 官方生命周期示意图