React 组件的生命周期是理解组件行为的关键。以下是主要阶段及方法:

一、生命周期阶段 🕰️

  1. 挂载阶段 (Mounting)

    • constructor():初始化状态和绑定方法
    • render():渲染UI
    • componentDidMount():挂载后执行逻辑
    React_Lifecycle
  2. 更新阶段 (Updating)

    • shouldComponentUpdate():决定是否重新渲染
    • render():重新渲染UI
    • componentDidUpdate():更新后执行逻辑
    React_Update_Lifecycle
  3. 卸载阶段 (Unmounting)

    • componentWillUnmount():清理资源
    React_Unmount_Lifecycle

二、Hooks 版本替代方案 🔄

  • useEffect 替代 componentDidMount/componentDidUpdate/componentWillUnmount
  • useLayoutEffect 用于布局相关的副作用
    useEffect_Lifecycle

三、最佳实践 ✅

  • 避免在 render 中执行耗时操作
  • 使用 React.memo 优化频繁渲染的组件
  • 查阅 /react/advanced 了解更高级用法

📌 生命周期方法在函数组件中已被Hooks逐步替代,建议优先使用React 17+的新兴API