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;

輸出

這將產生以下結果。

更新時間: 18-3-2021

679 次觀看

開啟您的職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.