當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


ReactJS componentWillUnmount()用法及代碼示例

當組件從DOM(文檔對象模型)中銷毀或卸載時,componentWillUnmount()方法允許我們執行React代碼。在React Life-cycle的Unmounting階段即組件卸載之前調用此方法。

所有清除(例如使計時器失效,取消網絡請求或清除在componentDidMount()中創建的訂閱)都應在componentWillUnmount()方法塊中進行編碼。

提示:切勿使用componentWillUnmount()方法調用setState()。

用法:

componentWillUnmount()

創建React應用程序:



步驟1:使用以下命令創建React應用程序:

npx create-react-app functiondemo

第2步:創建項目文件夾(即functiondemo)後,使用以下命令將其移至該文件夾:

cd functiondemo

項目結構:如下圖所示。

項目結構

例:在此示例中,我們將構建一個名稱顏色應用程序,當在DOM樹中呈現組件時,該應用程序將更改文本的顏色。

App.js:現在在App.js文件中寫下以下代碼。在這裏,App是我們編寫代碼的默認組件。

Javascript

import React from 'react';
class ComponentOne extends React.Component {
 
  // Defining the componentWillUnmount method
  componentWillUnmount() {
    alert('The component is going to be unmounted');
  }
 
  render() {
    return <h1>Hello Geeks!</h1>;
  }
}
 
class App extends React.Component {
  state = { display:true };
  delete = () => {
    this.setState({ display:false });
  };
 
  render() {
    let comp;
    if (this.state.display) {
      comp = <ComponentOne />;
    }
    return (
      <div>
        {comp}
        <button onClick={this.delete}>
          Delete the component
        </button>
      </div>
    );
  }
}
 
export default App;


注意:您可以在App.css文件中定義自己的樣式。

運行應用程序的步驟:從項目的根目錄中使用以下命令運行應用程序:



npm start

輸出:

參考: https://reactjs.org/docs/react-component.html#componentwillunmount

react-js-img

相關用法


注:本文由純淨天空篩選整理自rbbansal大神的英文原創作品 ReactJS componentWillUnmount() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。