ReactJS - componentWillUnmount() 方法



元件是我們 React 應用的構建塊。它們類似於樂高積木,我們將其組裝成更大的建築物。componentWillUnmount() 是每個元件都可用的生命週期方法之一。

componentWillUnmount 方法是 React 類元件的一部分。React 在元件從螢幕上移除或“解除安裝”之前呼叫它。這是一個用於清理任務的常用位置,例如取消資料獲取或停用訂閱。

語法

componentWillUnmount() {
   // Cleanup and resource release logic here
}

引數

componentWillUnmount 不接受任何引數。它是一個生命週期函式,當元件即將被解除安裝時,React 會呼叫它。

返回值

componentWillUnmount 函式不應返回任何內容。它用於執行清理操作並釋放資源,而不是返回值。

示例

示例

讓我們建立一個基本的示例應用來展示如何在 React 類元件中使用 componentWillUnmount 函式。在這個示例中,我們將建立一個計數器應用,它在元件掛載時啟動計時器,並在元件解除安裝時停止計時器。

import React, { Component } from 'react';

class App extends Component {
   state = {
      count: 0,
   };
   timerID = null;   
   componentDidMount() {
      
      // Start the timer when the component mounts
      this.timerID = setInterval(() => {
         this.setState((prevState) => ({ count: prevState.count + 1 }));
      }, 1000);
   }   
   componentWillUnmount() {
      // Stop the timer when the component unmounts
      clearInterval(this.timerID);
   }   
   render() {
      return (
         <div>
            <h1>Counter: {this.state.count}</h1>
         </div>
      );
   }
}

export default App;

輸出

counter_7

我們建立了一個 CounterApp 元件,它擴充套件了 Component。在 componentDidMount 方法中,我們使用 setInterval 啟動了一個計時器,每秒更新一次 count 狀態。這是一個簡單的計數器,每秒遞增一次。在 componentWillUnmount 方法中,我們使用 clearInterval 停止了計時器,以防止元件解除安裝時出現記憶體洩漏。render 方法顯示當前的計數器值。

此應用展示瞭如何使用 componentWillUnmount 函式來清理資源。在我們的例子中,它是在元件解除安裝時停止計時器。

示例 - 使用者資料應用

在此應用中,我們將有一個使用者資料顯示,並且 componentWillUnmount() 函式用於在元件解除安裝時可能需要的任何清理操作。

UserProfileApp.js

import React, { Component } from 'react';
import './App.css';

class UserProfileApp extends Component {
   state = {
      userProfile: {
         username: 'Akshay_Sharma',
         email: 'akshay@example.com',
      },
   };   
   componentDidMount() {
      
      // Fetch user profile data when the component mounts
   }   
   componentWillUnmount() {
      
      // Any cleanup needed for user profile app can be done here
      console.log('UserProfileApp will unmount');
   }   
   render() {
      const { username, email } = this.state.userProfile;
      return (
         <div className='App user-profile-container'>
            <h1>User Profile</h1>
            <p>Username: {username}</p>
            <p>Email: {email}</p>
         </div>
      );
   }
}

export default UserProfileApp;

App.css

.user-profile-container {
   max-width: 400px;
   margin: auto;
   padding: 20px;
   border: 1px solid #ccc;
   border-radius: 8px;
   box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
   background-color:rgb(224, 204, 178);
}
h1 {
   color: red;
}
p {
   margin: 8px 0;
   color: green;
}

輸出

user profile name

示例 - 倒計時應用

在此應用中,我們將有一個倒計時器,它在元件掛載時啟動,並在元件即將解除安裝時停止。所以此應用的程式碼如下:

CountdownTimerApp.js

import React, { Component } from 'react';
import './App.css'

class CountdownTimerApp extends Component {
   state = {
      time: 10,
   };
   timerID = null;   
   componentDidMount() {
      
      // Start the countdown timer when the component mounts
      this.timerID = setInterval(() => {
         this.setState((prevState) => ({ time: prevState.time - 1 }));
      }, 1000);
   }   
   componentWillUnmount() {
      
      // Stop the countdown timer when the component unmounts
      clearInterval(this.timerID);
   }   
   render() {
      return (
         <div className='App'>
            <h1>Countdown Timer: {this.state.time}s</h1>
         </div>
      );
   }
}

export default CountdownTimerApp;

輸出

countdown timer

componentWillUnmount() 方法用於在元件即將解除安裝時清除間隔或執行清理操作。

侷限性

在 React 的嚴格模式下進行開發時,React 可以使用 componentDidMount,立即呼叫 componentWillUnmount,然後再次呼叫 componentDidMount。這是一個用於識別 componentWillUnmount 問題並確保其正確複製 componentDidMount 行為的有用工具。

總結

componentWillUnmount 是 React 類元件中的一個方法,用於在從螢幕上清除元件之前清理資源。對於停止資料獲取和停用訂閱等操作,它是必需的。我們透過複製 componentDidMount 中的行為來確保我們的元件在其整個生命週期中都能順利執行。

reactjs_reference_api.htm
廣告