ReactJS - UNSAFE_componentWillMount() 方法



React 中的 componentWillMount() 函式就像元件出現在網頁上之前的準備步驟。它發生在元件顯示之前。此函式獲取資料,但需要注意的是,在元件第一次顯示之前,它不會提供任何結果。由於獲取資料可能需要一些時間,因此元件不會等待此階段完成才顯示自身。

在最新的 React 版本中,不再推薦使用 componentWillMount()。他們建議改用 componentDidMount()。如果我們確實想要使用 componentWillMount(),我們可以使用,但是我們必須將其稱為 UNSAFE_componentWillMount()。這就像一個警告標誌,提醒 React 開發者應該避免使用它。

語法

UNSAFE_componentWillMount() {
   //the action will come here that we want to execute
}

引數

此方法不接受任何引數。

返回值

此方法不應該返回任何值。

示例

示例 - 顯示警告訊息

藉助 UNSAFE_componentWillMount() 函式,這是一個在元件載入之前顯示警告的 React 應用示例。

import React, { Component } from 'react';

class App extends Component {
   UNSAFE_componentWillMount() {
      alert("This message will appear before the component loads.");
   }   
   render() {
      return (
         <div>
            <h1>Welcome to My React App</h1>
            <p>This is a simple application using UNSAFE_componentWillMount().</p>
         </div>
      );
   }
}

export default App;

輸出

welcome to my react app

這是一個簡單的 UNSAFE_componentWillMount() 應用示例,用於在網頁上載入 React 元件之前顯示訊息。請記住,在最新的 React 版本中,對於類似的功能,建議使用 componentDidMount() 而不是 UNSAFE_componentWillMount()。

示例 - 資料獲取應用

在這個示例中,我們將建立一個元件,在即將掛載時從 JSONPlaceholder API 獲取資料。然後將獲取到的資料儲存在元件的狀態中,元件在資料可用後呈現資料。因此,此應用的程式碼如下:

import React, { Component } from 'react';
import './App.css'

class DataFetchingApp extends Component {
   constructor() {
      super();
      this.state = {
         data: null,
      };
   }   
   UNSAFE_componentWillMount() {
      // fetching data from an API
      fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then((response) => response.json())
      .then((data) => {
         this.setState({ data });
      })
      .catch((error) => console.error('Error fetching data:', error));
   }   
   render() {
      const { data } = this.state;
      
      return (
         <div className='App'>
            <h1>Data Fetching App</h1>
            {data ? (
               <div>
                  <h2>Data from API:</h2>
                  <p>Title: {data.title}</p>
                  <p>User ID: {data.userId}</p>
                  <p>Completed: {data.completed ? 'Yes' : 'No'}</p>
               </div>
               ) : (
               <p>Loading data...</p>
               )}
         </div>
      );
   }
}

export default DataFetchingApp;

App.css

.App {
   align-items: center;
   justify-content: center;
   margin-left: 500px;
   margin-top: 50px;
}
h1 {
   color: red;
}
p {
   margin: 8px 0;
   color: green;
}

輸出

data fetching app

在這個 React 應用中,我們使用了 UNSAFE_componentWillMount() 來在元件掛載之前從 API 獲取資料。因此,我們使用了 API 來獲取資料。

示例 - 倒計時器應用

現在我們還有一個簡單的 React 應用,它使用 UNSAFE_componentWillMount() 來設定倒計時器。在這個應用程式中,我們將有一個計時器,它將倒計時 10 秒,10 秒後,它將在螢幕上顯示一條警告訊息,表明時間已達到零。因此,此應用的程式碼如下:

import React, { Component } from 'react';
import './App.css';

class CountdownTimerApp extends Component {
   constructor() {
      super();
      this.state = {
         seconds: 10,
      };
   }   
   UNSAFE_componentWillMount() {
      this.startTimer();
   }   
   startTimer() {
      this.timerInterval = setInterval(() => {
         this.setState((prevState) => ({
            seconds: prevState.seconds - 1,
         }), () => {
         if (this.state.seconds === 0) {
            clearInterval(this.timerInterval);
            alert('Countdown timer reached zero!');
         }
         });
      }, 1000);
   }
   
   render() {
      return (
         <div className='App'>
            <h1>Countdown Timer App</h1>
            <p>Seconds remaining: {this.state.seconds}</p>
         </div>
      );
   }
}

export default CountdownTimerApp;

輸出

countdown timer app countdown timer reached

在這個示例中,元件在 UNSAFE_componentWillMount() 生命週期方法中開始倒計時器。每秒,計時器都會遞減 seconds 狀態。當倒計時達到零時,間隔被清除並顯示警報。

限制

  • 如果元件使用 getDerivedStateFromProps 或 getSnapshotBeforeUpdate,則不會呼叫此方法。

  • UNSAFE_componentWillMount 不能保證元件在某些當前 React 場景(如 Suspense)中會被掛載。

  • 它被稱為“不安全”是因為在某些情況下,React 可以丟棄正在進行的元件樹並重建它,這使得 UNSAFE_componentWillMount 變得不可靠。

  • 如果我們需要執行依賴於元件掛載的活動,請改用 componentDidMount。

  • UNSAFE_componentWillMount 是伺服器端渲染時唯一執行的生命週期方法。

  • 對於大多數實際用途,它與建構函式類似,因此最好使用建構函式來實現等效邏輯。

總結

UNSAFE_componentWillMount() 是一個較舊的 React 生命週期函式,用於元件載入前的任務,但在現代 React 程式設計中,建議遵循當前的最佳實踐,併為此類任務使用 componentDidMount()。

reactjs_reference_api.htm
廣告