ReactJS - UNSAFE_componentWillUpdate() 方法



在 Web 開發中,UNSAFE_componentWillUpdate() 函式充當警告。它在我們即將修改網站一部分時出現。

請記住,此警告僅在更新任何內容時顯示,而不在首次建立時顯示。因此,UNSAFE_componentWillUpdate() 充當警告,幫助我們檢測更新網站時出現的問題。

語法

UNSAFE_componentWillUpdate(nextProps, nextState)

引數

此方法接受兩個引數:nextProps 和 nextState。

  • nextProps − 這些是我們的 Web 元件將獲得的新特性(如資訊)。它就像獲得一套新的指令。

  • nextState − 這反映了我們元件的新狀態。它類似於瞭解當前情況。

返回值

UNSAFE_componentWillUpdate() 不返回任何結果。它更像是進行更改之前的起點,因此它不提供結果或答案。

示例

示例 1

在這個示例中,我們將在 React 應用中使用 UNSAFE_componentWillUpdate() 函式建立一個簡單的示例。

我們將有一個名為 App 的基本 React 元件。它允許我們透過點選按鈕來更改頁面的背景顏色。UNSAFE_componentWillUpdate() 函式將檢測背景顏色的變化並相應地調整頁面的背景顏色。

import React, { Component } from 'react';

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         backgroundColor: 'white',
      };
   }
   
   // This is the UNSAFE_componentWillUpdate() function.
   UNSAFE_componentWillUpdate(nextProps, nextState) {
      if (nextState.backgroundColor !== this.state.backgroundColor) {
         document.body.style.backgroundColor = nextState.backgroundColor;
      }
   }   
   handleChangeColor = (color) => {
      this.setState({ backgroundColor: color });
   }
   
   render() {
      return (
         <div>
            <h1>Color Change App</h1>
            <button onClick={() => this.handleChangeColor('red')}>Change to Red</button>
            <button onClick={() => this.handleChangeColor('blue')}>Change to Blue</button>
            <button onClick={() => this.handleChangeColor('green')}>Change to Green</button>
         </div>
      );
   }
}

export default App;

輸出

color change app

示例 2

在這個示例中,我們將使用 UNSAFE_componentWillUpdate() 函式將溫度從攝氏度更新為華氏度。我們可以輸入攝氏度或華氏度的溫度,程式將立即調整另一個溫度值。例如,如果我們輸入攝氏度溫度,應用程式將顯示相應的華氏度溫度,反之亦然。當我們輸入新的溫度時,它使用 UNSAFE_componentWillUpdate() 方法處理轉換。

以下是相同的程式碼:

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

class TempConverterApp extends Component {
      constructor(props) {
      super(props);
      this.state = {
         celsius: 0,
         fahrenheit: 32,
      };
   }
   
   // Usage of UNSAFE_componentWillUpdate() to update the temperature values
   UNSAFE_componentWillUpdate(nextProps, nextState) {
      if (nextState.celsius !== this.state.celsius) {
         
         // Convert Celsius to Fahrenheit
         nextState.fahrenheit = (nextState.celsius * 9) / 5 + 32;
      } else if (nextState.fahrenheit !== this.state.fahrenheit) {
         
         // Convert Fahrenheit to Celsius
         nextState.celsius = ((nextState.fahrenheit - 32) * 5) / 9;
      }
   }   
   handleChangeCelsius = (value) => {
      this.setState({ celsius: value });
   };   
   handleChangeFahrenheit = (value) => {
      this.setState({ fahrenheit: value });
   };
   
   render() {
      return (
         <div className='App'>
            <h1>Temperature Converter</h1>
            <label>
               Celsius:
               <input
                  type="number"
                  value={this.state.celsius}
                  onChange={(e) => this.handleChangeCelsius(e.target.value)}
               />
               </label>
               <br />
            <label>
               Fahrenheit:
               <input
                  type="number"
                  value={this.state.fahrenheit}
                  onChange={(e) => this.handleChangeFahrenheit(e.target.value)}
               />
            </label>
         </div>
      );
   }
}

export default TempConverterApp;

輸出

temperature converter

普通文字:用於普通文字。

示例 3

此應用程式是一個簡單的計數器應用程式,可以向上和向下計數。有兩個按鈕:一個用於增加計數,另一個用於減少計數。程式還將告訴我們當前計數是奇數還是偶數。它透過呼叫 UNSAFE_componentWillUpdate() 方法來更新基於計數是奇數還是偶數的訊息。如果我們有一個偶數,它將顯示“偶數計數”,如果我們有一個奇數,它將顯示“奇數計數”。

因此,此應用程式的程式碼如下:

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

class CounterApp extends Component {
   constructor(props) {
      super(props);
      this.state = {
         count: 0,
         message: '',
      };
   }
   
   // Usage of UNSAFE_componentWillUpdate() to update the message based on the count value
   UNSAFE_componentWillUpdate(nextProps, nextState) {
      if (nextState.count !== this.state.count) {
         nextState.message = nextState.count % 2 === 0 ? 'Even Count' : 'Odd Count';
      }
   }   
   handleIncrement = () => {
      this.setState((prevState) => ({ count: prevState.count + 1 }));
   };   
   handleDecrement = () => {
      this.setState((prevState) => ({ count: prevState.count - 1 }));
   };
   
   render() {
      return (
         <div className='App'>
            <h1>Counter App</h1>
            <p>{this.state.message}</p>
            <button onClick={this.handleIncrement}>Increment</button>
            <button onClick={this.handleDecrement}>Decrement</button>
            <p>Count: {this.state.count}</p>
         </div>
      );
   }
}

export default CounterApp;

輸出

counter app even odd

注意

因此,我們可以看到上面所示的輸出影像中,有兩個按鈕可用:一個用於遞增,另一個用於遞減。並且根據奇數和偶數計數顯示訊息。

總結

UNSAFE_componentWillUpdate() 是一個 React 函式,它在元件更新和重新渲染之前不久使用。它使我們有機會為將來的更改做好準備。

reactjs_reference_api.htm
廣告