ReactJS – componentWillUpdate() 方法


在本文中,我們將看到如何在 DOM 樹中更新元件之前執行函式。

此方法在 React 生命週期更新階段使用。此函式通常在元件更新之前或傳遞給元件的狀態或屬性發生更改時呼叫。不要在此函式中呼叫 setState() 方法。如果 shouldComponentUpdate() 方法返回 false,則此方法將不會被呼叫。

請注意:此方法現已棄用。

語法

UNSAFE_componentWillUpdate(nextProps, nextState)

示例

在此示例中,我們將構建一個改變顏色的 React 應用程式,當元件在 DOM 樹中更新時,它會呼叫 componentWillUpdate 方法。

以下示例中的第一個元件是 App。此元件是 ChangeName 元件的父元件。我們正在單獨建立 ChangeName,並新增到我們的 App 元件中的 JSX 樹中。因此,只需要匯出 App 元件即可。

App.jsx

import React from 'react';

class App extends React.Component {
   state = { color: 'green' };
   render() {
      setTimeout(() => {
         this.setState({ color: 'wheat' });
      }, 4000);
      return (
         <div>
            <h1>Tutorialspoint</h1>
            <ChangeName color={this.state.color} />
         </div>
      );
   }
}
class ChangeName extends React.Component {
   UNSAFE_componentWillUpdate(nextProps, nextState) {
      console.log('Component will be updated soon');
   }
   render() {
      console.log('ChangeName component is called');
      return (
         <div>
            <h1 style={{ color: this.props.color }}>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;

輸出

這將產生以下結果。

更新於:18-03-2021

4K+ 瀏覽量

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.