跳至主要内容

[react] 生命週期(life cycle)

內容可能過時

本文描述的是 Class Component 的生命週期方法。其中 componentWillMount、componentWillReceiveProps、componentWillUpdate 已在 React 16.3 被標記為棄用,並在 React 18 中正式移除。現代 React 開發建議使用 Function Component 搭配 useEffect、useLayoutEffect 等 Hooks 來處理副作用和生命週期邏輯。

建議使用的生命週期架構如下:

:thumbsup: React LifeCycle Methods Diagram

Mounting LifeCycle​

  • componentWillMount
  • render
  • componentDidMount

在 React 中,適合在 componentDidMount 時來透過 AJAX 存取資料,或者說,在 componentDidMount 時,最適合 React app 和其他外部的應用程式產生連結,不論是 Web APIs、其他 JS 套件、或者 setTimeout, setInterval。

export class Flashy extends React.Component {
componentWillMount() {
alert('AND NOW, FOR THE FIRST TIME EVER... FLASHY!!!!');
}

componentDidMount() {
alert('YOU JUST WITNESSED THE DEBUT OF... FLASHY!!!!!!!');
}

render() {
alert('Flashy is rendering!');

return <h1 style={{ color: this.props.color }}>OOH LA LA LOOK AT ME I AM THE FLASHIEST</h1>;
}
}

Updating/Unmounting Lifecycle​

  • componentWillReceiveProps(nextProps):第一次元件轉譯時不會呼叫到,當元件更新時,在 render 開始前呼叫。
  • shouldComponentUpdate(nextProps, nextState)
  • componentWillUpdate(nextProps, nextState)
  • render
  • componentDidUpdate(prevProps, prevState)
  • componentWillUnmount

shouldComponentUpdate(nextProps, nextState)​

當元件更新時,在 componentWillReceiveProps 之後,在 render 之前呼叫到。在這裡面可以回傳 true 或 false,當回傳 false 時,該元件就不會繼續更新。

componentWillUpdate(nextProps, nextState)​

在 shouldComponentUpdate 和 render 之間被呼叫到。適合用在和 React 無關的設定,像是檢查 window 的尺寸。

componentDidUpdate(prevProps, prevState)​

在任何轉譯的 HTML 完成載入後。通常會用在和 React 環境外的東西互動時使用,像是瀏覽器或 Web APIs,這和 componentWillUpdate 很類似,差別只在於 render 之後呼叫。

export class Example extends React.Component {
// 可以代入參數,取得即將進來的 props
componentWillReceiveProps(nextProps) {
// do something here ...
}

render() {
return <h1>{this.props.text}</h1>;
}
}

// The first render won't trigger
// componentWillReceiveProps:
const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<Example text="Hello world" />);

完整的生命週期架構​

下圖是 React 中,完整的生命週期架構,但建議使用官方建議的就好:

有父子層元件的情況下​

假設有父層元件...