React 中基於 Hooks 的 componentDidUpdate() 生命週期方法的替代方案

Irakli Tchigladze 2023年1月30日
  1. React 中類元件中的生命週期方法
  2. 在 React 中如何使用 Hooks 實現 componentDidUpdate()
React 中基於 Hooks 的 componentDidUpdate() 生命週期方法的替代方案

React 是一個基於元件的庫,用於使用可重用元件構建漂亮的介面。除了 Virtual DOM 和狀態管理等許多有用的功能外,React 還允許我們在元件生命週期的某個階段執行某些程式碼。

React 中類元件中的生命週期方法

生命週期方法允許我們執行副作用程式碼,例如從外部源載入資料、設定訂閱或其他功能。

例如,componentDidMount() 生命週期方法允許你在元件被掛載(或者,換句話說,第一次渲染)時執行程式碼。

你可以在 codesandbox 上檢視演示。

import { Component, useRef, useEffect } from "react";

export default class App extends Component {
  componentDidMount() {
    console.log("mounted!");
  }
  render() {
    return <h1>Hello World</h1>;
  }
}

如果你檢查控制檯,你會看到 console.log() 函式的字串引數已記錄到控制檯。

另一個主要的生命週期方法是 componentDidUpdate(),它執行每個元件狀態更改,觸發更新。讓我們看一個例子。

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      boolean: false
    };
  }
  componentDidMount() {
    console.log("mounted!");
  }
  componentDidUpdate() {
    console.log("updated!");
  }
  render() {
    return (
      <button onClick={() => this.setState({ boolean: !this.state.boolean })}>
        Change the State
      </button>
    );
  }
}

該元件包含一個按鈕,用於更改狀態值。每次單擊 demo 中的按鈕時,狀態都會發生變化,從而觸發更新。如果你在控制檯中檢視,每次狀態更改時,字串 "updated" 都會記錄到控制檯。

你應該閱讀本文以瞭解有關類元件的典型生命週期元件的更多資訊。

在 React 中如何使用 Hooks 實現 componentDidUpdate()

生命週期方法不適用於功能元件。但是,useEffect() 掛鉤是上述方法的替代方法。

為了在功能元件中重新建立 componentDidUpdate() 生命週期方法的功能,我們可以使用 useRef() 掛鉤在功能元件中建立例項變數。

然後我們可以有條件地檢查變數的 current 屬性以在功能元件的不同生命週期中執行程式碼。

讓我們看一個例子。

function SomeComponent() {
  const status = useRef();
  useEffect(() => {
    if (!status.current){
        // componentDidMount
      status.current = true
    }
    else {
        // componentDidUpdate
      console.log("updated")
    }
  });
  return <h1>A sample component</h1>;
}

在這個例子中,我們使用了兩個條件塊:一個在元件掛載時執行程式碼,另一個在元件更新時執行。

第一次建立元件時,可以將其 current 屬性設定為 true,之後每次呼叫 useEffect() 函式中的回撥函式時,都會執行 else 中的程式碼堵塞。

你可以在 codesandbox 上檢視演示。

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn

相關文章 - React Hooks