- ReactJS 教程
- ReactJS - 首頁
- ReactJS - 簡介
- ReactJS - 路線圖
- ReactJS - 安裝
- ReactJS - 特性
- ReactJS - 優點與缺點
- ReactJS - 架構
- ReactJS - 建立 React 應用
- ReactJS - JSX
- ReactJS - 元件
- ReactJS - 巢狀元件
- ReactJS - 使用新建立的元件
- ReactJS - 元件集合
- ReactJS - 樣式
- ReactJS - 屬性 (props)
- ReactJS - 使用屬性建立元件
- ReactJS - props 驗證
- ReactJS - 建構函式
- ReactJS - 元件生命週期
- ReactJS - 事件管理
- ReactJS - 建立一個事件感知元件
- ReactJS - 在 Expense Manager 應用中引入事件
- ReactJS - 狀態管理
- ReactJS - 狀態管理 API
- ReactJS - 無狀態元件
- ReactJS - 使用 React Hooks 進行狀態管理
- ReactJS - 使用 React Hooks 的元件生命週期
- ReactJS - 佈局元件
- ReactJS - 分頁
- ReactJS - Material UI
- ReactJS - Http 客戶端程式設計
- ReactJS - 表單程式設計
- ReactJS - 受控元件
- ReactJS - 非受控元件
- ReactJS - Formik
- ReactJS - 條件渲染
- ReactJS - 列表
- ReactJS - Keys
- ReactJS - 路由
- ReactJS - Redux
- ReactJS - 動畫
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - 表格
- ReactJS - 使用 Flux 管理狀態
- ReactJS - 測試
- ReactJS - CLI 命令
- ReactJS - 構建和部署
- ReactJS - 示例
- Hooks
- ReactJS - Hooks 簡介
- ReactJS - 使用 useState
- ReactJS - 使用 useEffect
- ReactJS - 使用 useContext
- ReactJS - 使用 useRef
- ReactJS - 使用 useReducer
- ReactJS - 使用 useCallback
- ReactJS - 使用 useMemo
- ReactJS - 自定義 Hooks
- ReactJS 高階
- ReactJS - 可訪問性
- ReactJS - 程式碼分割
- ReactJS - Context
- ReactJS - 錯誤邊界
- ReactJS - 轉發 Refs
- ReactJS - Fragments
- ReactJS - 高階元件
- ReactJS - 與其他庫整合
- ReactJS - 效能最佳化
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - 無需 ES6 ECMAScript 的 React
- ReactJS - 無需 JSX 的 React
- ReactJS - Reconciliation (協調)
- ReactJS - Refs 和 DOM
- ReactJS - Render Props
- ReactJS - 靜態型別檢查
- ReactJS - Strict Mode (嚴格模式)
- ReactJS - Web Components
- 其他概念
- ReactJS - 日期選擇器
- ReactJS - Helmet
- ReactJS - 內聯樣式
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - 輪播圖
- ReactJS - 圖示
- ReactJS - 表單元件
- ReactJS - 參考 API
- ReactJS 有用資源
- ReactJS - 快速指南
- ReactJS - 有用資源
- ReactJS - 討論
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;
輸出
示例 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;
輸出
示例 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;
輸出
限制
如果我們使用 forceUpdate,React 將在不檢查 shouldComponentUpdate 的情況下重新整理。
總結
對於 React 元件,forceUpdate 的作用類似於重新整理按鈕。雖然我們不會經常使用它,但在元件從外部來源接收資料時它會很有用。記住,通常最好讓 React 自動處理更新,但是如果我們需要更多控制,forceUpdate 是可用的。