ReactJS - forceUpdate() 方法



React 中的元件充當網站或應用程式的構建塊。它們可以顯示多種內容並執行不同的操作。通常,元件只有在其自身狀態或從外部獲取的資訊(稱為 props)發生變化時才會更改或重新渲染。

React 元件只有在其狀態或傳遞給它的 props 發生變化時才會重新渲染,但是如果我們需要在任何資料變化時重新渲染元件,則可以使用 React 的 forceUpdate() 方法。呼叫 forceUpdate() 將強制重新渲染元件,忽略 shouldComponentUpdate() 方法,而是呼叫元件的 render() 方法。

因此,forceUpdate() 是一種使 React 元件重新整理自身的方法,即使它認為不需要重新整理也是如此。

語法

forceUpdate(callbackFunc)

引數

callbackFunc − 這是一個可選的回撥函式。如果我們定義一個回撥函式,React 將在更新提交後執行它。

返回值

此函式不返回任何值。

示例

示例 1

讓我們建立一個基本的 React 應用,展示如何使用 forceUpdate 函式。在這個示例中,我們將有一個元件從外部 API 獲取一個隨機數,並在單擊按鈕時更新 UI。

NumberDisplay.js

import React, { Component } from 'react';

class NumberDisplay extends Component {
   constructor() {
      super();
      this.state = {
         randomNumber: null,
      };
   }   
   fetchData = async () => {
      // An API call to get a random number
      const response = await fetch('https://www.random.org/integers/?num=1&min=1&max=100&format=plain');
      const data = await response.text();
      this.setState({ randomNumber: parseInt(data) });
   };   
   forceUpdateHandler = () => {
      // Use forceUpdate to manually update the component
      this.forceUpdate();
   };   
   render() {
      return (
         <div>
            <h1>Random Number: {this.state.randomNumber}</h1>
            <button onClick={this.fetchData}>Fetch New Number</button>
            <button onClick={this.forceUpdateHandler}>Force Update</button>
         </div>
      );
   }
}

export default NumberDisplay;

App.js

import React from 'react';
import NumberDisplay from './NumberDisplay';

function App() {
   return (
      <div>
         <h1>ForceUpdate Example App</h1>
         <NumberDisplay />
      </div>
   );
}
export default App;

輸出

forceupdate example

示例 2

假設我們有一個簡單的計數應用程式。這個計數器應用程式在螢幕上顯示一個數字,從 0 開始。我們可以透過單擊“增加計數”按鈕來增加計數。但是,還有一個標記為“強制更新”的按鈕。當我們單擊它時,即使我們沒有增加計數,應用程式也會重新整理並再次顯示當前計數。這裡使用 forceUpdate() 函式來確保顯示始終是最新的。

import React from 'react';

class CounterApp extends React.Component {
   constructor() {
      super();
      this.state = { count: 0 };
   }   
   increaseCount() {
      this.setState({ count: this.state.count + 1 });
   }   
   forceUpdateCounter() {
      this.forceUpdate();
   }   
   render() {
      return (
         <div>
            <p>Count: {this.state.count}</p>
            <button onClick={() => this.increaseCount()}>Increase Count</button>
            <button onClick={() => this.forceUpdateCounter()}>Force Update</button>
         </div>
      );
   }
}

export default CounterApp;

輸出

force update

示例 3

現在讓我們建立一個訊息應用程式。此程式在螢幕上顯示一條訊息,最初設定為“Hello, world!”。透過單擊“更改訊息”按鈕,我們可以更改訊息。但是有一個“強制更新”按鈕。當我們單擊此按鈕時,應用程式將重新整理並顯示當前訊息。為了實現這種重新整理行為,需要 forceUpdate() 函式。

import React from "react";

class MessageApp extends React.Component {
   constructor() {
      super();
      this.state = { message: "Hello, world!" };
   }   
   changeMessage(newMessage) {
      this.setState({ message: newMessage });
   }   
   forceUpdateMessage() {
      this.forceUpdate();
   }   
   render() {
      return (
         <div>
            <p>{this.state.message}</p>
            <button onClick={() => this.changeMessage("New Message")}>
               Change Message
            </button>
            <button onClick={() => this.forceUpdateMessage()}>Force Update</button>
         </div>
      );
   }
}

export default MessageApp;

輸出

new message hello

限制

如果我們使用 forceUpdate,React 將在不檢查 shouldComponentUpdate 的情況下重新整理。

總結

對於 React 元件,forceUpdate 的作用類似於重新整理按鈕。雖然我們不會經常使用它,但在元件從外部來源接收資料時它會很有用。記住,通常最好讓 React 自動處理更新,但是如果我們需要更多控制,forceUpdate 是可用的。

reactjs_reference_api.htm
廣告
© . All rights reserved.