React 組件的生命周期分為三個階段:掛載(Mounting)、更新(Updating) 和 卸載(Unmounting)。以下是類組件生命周期的詳細說明(基于 React 16.3+ 版本):
一、掛載階段(Mounting)
組件實例被創建并插入 DOM 時的流程:
- constructor(props)
○ 用途:初始化狀態(this.state)或綁定方法。
○ 注意:必須調用 super(props),否則 this.props 會未定義。
○ 避免副作用(如 API 調用),應在 componentDidMount 中進行。 - static getDerivedStateFromProps(nextProps, prevState)
○ 用途:根據新的 props 更新 state。
○ 是靜態方法,無法訪問 this,必須返回一個對象更新 state 或返回 null 不更新。
○ 替代舊版 componentWillReceiveProps。 - render()
○ 用途:返回 JSX,描述 UI 結構。
○ 必須為純函數,不能修改組件狀態或直接與 DOM 交互。 - componentDidMount()
○ 用途:組件已掛載到 DOM 后調用。
○ 常見操作:發起網絡請求、添加事件監聽、操作 DOM 等副作用。
二、更新階段(Updating)
當組件的 props 或 state 發生變化時觸發:
- static getDerivedStateFromProps(nextProps, prevState)
○ 同掛載階段,在每次渲染前觸發(包括初始掛載和更新)。 - shouldComponentUpdate(nextProps, nextState)
○ 用途:決定是否重新渲染組件(默認返回 true)。
○ 返回 false 可跳過本次渲染及后續生命周期方法(如 render, componentDidUpdate)。
○ 性能優化:避免不