运行阶段生命周期调用顺序?

React 运行阶段(Mount + Update)生命周期调用顺序如下,两种写法分别列出来(class 组件 和 函数组件 Hook 思维模型)。

React Class 组件(运行阶段)生命周期调用顺序

一、挂载(Mounting)阶段

组件首次渲染时执行:

  • constructor()

  • static getDerivedStateFromProps()

  • render()

  • componentDidMount()

此时 DOM 已挂载,可安全进行:请求接口、DOM 操作、订阅事件 等。

最适合做服务端数据请求的生命周期就是 componentDidMount()

二、更新(Updating)阶段

组件因 state/props 变化重新渲染:

  1. static getDerivedStateFromProps()

  2. shouldComponentUpdate()

  3. render()

  4. getSnapshotBeforeUpdate()

  5. componentDidUpdate()

三、卸载(Unmounting)阶段

componentWillUnmount()

完整流程示意图
Mount(首次渲染)
constructor →
getDerivedStateFromProps →
render →
componentDidMount
Update(更新)
getDerivedStateFromProps →
shouldComponentUpdate →
render →
getSnapshotBeforeUpdate →
componentDidUpdate

React 函数组件运行逻辑(理解对照版)

函数组件只有 useEffect 模拟运行阶段:

挂载阶段
function Component()
useEffect(..., [])        ← 等价于 componentDidMount
更新阶段
function Component()
useEffect(..., [deps])    ← 等价于 componentDidUpdate
卸载阶段
return () => {}           ← cleanup 清理函数等价于 componentWillUnmount

最常用记忆口诀

挂载阶段:

constructor → render → componentDidMount

更新阶段:

render → componentDidUpdate

卸载阶段:

componentWillUnmount

posted @ 2025-11-14 09:09  煜火  阅读(4)  评论(0)    收藏  举报