生命周期

Youky ... 2025-2-20 前端
  • React
About 2 min

# 生命周期

# 总览

阶段 生命周期方法 说明
挂载 Mounting constructorstatic getDerivedStateFromPropsrendercomponentDidMount 组件创建并插入 DOM 的过程
更新 Updating static getDerivedStateFromPropsshouldComponentUpdaterendergetSnapshotBeforeUpdatecomponentDidUpdate 组件接收新的 props 或 state 后的更新过程
卸载 Unmounting componentWillUnmount 组件从 DOM 移除前调用,用于清理资源
错误处理 Error static getDerivedStateFromErrorcomponentDidCatch 捕获子组件渲染、生命周期或构造函数错误

# 具体介绍

  • getDerivedStateFromProps:props 变化时触发,根据 props 计算 state,包括初始渲染和更新。静态方法,无法调用 this,不能进行副作用处理
  • shouldComponentUpdate:组件更新前触发,通过返回值决定是否重新渲染(返回 false 本次不更新),用于性能优化
  • getSnapshotBeforeUpdate:DOM 更新前触发,作用是在 React 进行 DOM 更新之前获取一些快照数据。其返回值会作为 componentDidUpdate 的第三个参数。不能在内部修改 DOM,因为这时的修改可能会在后续被覆盖
    • 实际应用场景:保持滚动条位置(如消息列表更新后,动态计算滚动位置)
  • componentDidUpdate:DOM 更新后触发
  • componentWillUnmount:组件卸载前触发,此时可以访问 DOM。作用:清理定时器、事件监听
  • getDerivedStateFromError:组件发生错误时,用于更新 state,触发重新渲染来显示兜底 UI,不能执行副作用操作
  • componentDidCatch:用于记录异常信息(上报),不影响 UI

# 有哪些生命周期的功能,在函数组件中无法实现对等的功能

生命周期 函数组件中的近似替代 无法实现的效果
getDerivedStateFromProps 通过 useEffect + useState 可以实现在 props 变化时更新 state getDerivedStateFromProps 是在 render 前同步执行的,useEffect 是在 render 后异步执行的
shouldComponentUpdate 使用 React.memo() / useMemo() 可以优化 props 改变时的渲染时机 无法阻止 state 改变时的渲染
getSnapshotBeforeUpdate useLayoutEffect 在DOM 更新后,浏览器绘制前执行 无法返回快照值给 useEffect 使用
componentDidCatch/getDerivedStateFromError 使用 ErrorBoundary (类组件)包裹根组件 需要借助类组件
Last update: February 22, 2025 12:19
Contributors: Youky1