挂载阶段:getDerivedStateFromProps 根据新的 props 更新 state,适用于 state 依赖 props 的罕见场景(如表单控件的默认值)。 static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.type !== prevState.type) { return { type: nextProps.type }; // 更新 state } return null; // 不更新} getDerivedStateFromProps 是 React 16.3 版本引入的新生命周期方法,​用于替代旧生命周期方法 componentWillReceiveProps ​解决旧方法的设计缺陷 ​派生状态的滥用:开发者常通过 componentWillReceiveProps 无脑将 props 复制到 state,导致 state 与 props 的同步逻辑混乱,引发难以追踪的 Bug(如输入框内容被意外重置) ​副作用隐患:旧方法允许在 componentWillReceiveProps 中执行副作用(如网络请求),但这类操作可能破坏渲染的纯函数特性 新旧方法对比 ​特性 componentWillReceiveProps(旧) getDerivedStateFromProps(新) ​调用时机 父组件更新或setState触发 同左,但仅在props或state变化时触发 ​访问实例 (this) 支持(可通过this.props访问旧值) ​不支持​(静态方法,仅通过参数操作) ​返回值 无(需手动调用setState) ​必须返回对象或null​(直接更新state) ​副作用支持 允许(如发起请求) ​禁止​(需纯函数,仅用于派生状态) ​异步渲染兼容性 可能因多次调用导致数据不一致 安全(无副作用,逻辑可预测) 更新阶段:getSnapshotBeforeUpdate(prevProps, prevState) 在 DOM 更新前捕获信息(如滚动位置),返回值传递给 componentDidUpdate。 componentDidUpdate(prevProps, prevState, snapshot)

补充

补充:React 16.3+ 调整了生命周期,弃用了 componentWillMount、componentWillReceiveProps、componentWillUpdate 三个带「Will」的方法,统一替换为带「Did」或在 render 阶段触发的 API,目的是配合 Fiber 的异步渲染、避免副作用破坏渲染纯度。

完整生命周期(类组件):

  • 挂载阶段:constructor → static getDerivedStateFromProps → render → componentDidMount
  • 更新阶段(props/state 变化):static getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate
  • 卸载阶段:componentWillUnmount
  • 错误边界:static getDerivedStateFromError、componentDidCatch

对比表:

旧 API(16.3 之前)新 API(16.3+)
componentWillMountconstructor + componentDidMount
componentWillReceivePropsstatic getDerivedStateFromProps
componentWillUpdategetSnapshotBeforeUpdate + componentDidUpdate

补充:函数组件没有生命周期,对应概念是 useEffect(异步副作用)和 useLayoutEffect(同步布局副作用),依赖项控制执行时机。