ReactJS - forceUpdate() 方法
在本文中,我們將瞭解如何透過強制重新渲染一個元件來執行一個函式。
React 生命週期中的元件僅在其傳入的道具或其狀態發生變化時重新渲染,但要強制渲染元件,請使用 build it forceUpdate 方法。此方法會覆蓋元件中定義的 shouldComponentUpdate 方法,但會考慮子元件中定義的 shouldComponentUpdate 方法。
語法
component.forceUpdate(callback)
示例
在此示例中,我們將構建一個 React 應用程式,該應用程式會在按鈕單擊時強制重新渲染。
App.jsx
import React from 'react';
class App extends React.Component {
update = () => {
// calling the forceUpdate() method
this.forceUpdate();
};
render() {
console.log('Component is rendered');
return (
<>
<h2>TutorialsPoint</h2>
<button onClick={this.update}>Render</button>
</>
);
}
}
export default App;輸出
這將產生以下結果。

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP