React 组件的生命周期是理解组件行为的关键。以下是主要阶段及方法:
一、生命周期阶段 🕰️
挂载阶段 (Mounting)
constructor()
:初始化状态和绑定方法render()
:渲染UIcomponentDidMount()
:挂载后执行逻辑
更新阶段 (Updating)
shouldComponentUpdate()
:决定是否重新渲染render()
:重新渲染UIcomponentDidUpdate()
:更新后执行逻辑
卸载阶段 (Unmounting)
componentWillUnmount()
:清理资源
二、Hooks 版本替代方案 🔄
useEffect
替代componentDidMount
/componentDidUpdate
/componentWillUnmount
useLayoutEffect
用于布局相关的副作用
三、最佳实践 ✅
- 避免在
render
中执行耗时操作 - 使用
React.memo
优化频繁渲染的组件 - 查阅 /react/advanced 了解更高级用法
📌 生命周期方法在函数组件中已被Hooks逐步替代,建议优先使用React 17+的新兴API