ReactJS - componentDidCatch() 方法



React 是一個流行的 JavaScript 庫,用於建立使用者介面。在建立 React 應用時,我們可能會遇到程式碼錯誤。當這些錯誤發生在 React 元件中時,正確處理它們可能是一項艱鉅的任務。這就是 componentDidCatch 函式可以發揮作用的地方。因此,componentDidCatch 捕獲我們元件中的錯誤並防止我們的整個應用崩潰。所以我們將透過一個例子來了解它是如何工作的。

什麼是 componentDidCatch?

componentDidCatch 是一個可以在 React 元件中定義的函式。其主要功能是檢測任何元件子元素中的錯誤,無論該子元素在元件樹中位於何處。

當任何子元件中發生錯誤時,React 將呼叫 componentDidCatch。它給了我們一個響應錯誤的機會。

componentDidCatch 的一個常見用法是記錄錯誤。在生產環境中,這可以傳送到錯誤報告服務,使我們能夠跟蹤和修復問題。

語法

componentDidCatch(error, info)

引數

componentDidCatch 函式使用兩個引數:error 和 info。

  • error - 這是丟擲的錯誤。它通常是 Error 物件的一個例項,但也可能是字串或 null。

  • info - 這是有關錯誤的資料。它提供了一個堆疊跟蹤,指示問題發生的位置以及涉及哪些元件。

返回值

componentDidCatch 函式不返回任何內容。它主要用於指示錯誤不產生結果。

如何使用它?

我們將建立一個應用並使用 componentDidCatch 來展示其用法 -

在這個應用中,我們有一個 MyComponent,它在其 componentDidMount 函式中故意丟擲一個錯誤以獲取錯誤。我們將在 ErrorBoundary 中使用 MyComponent,它將捕獲並處理 MyComponent 中發生的任何錯誤。如果 MyComponent 中發生錯誤,ErrorBoundary 將顯示一個自定義的回退 UI,其中包含錯誤訊息。

示例

示例

import React from 'react';

class MyComponent extends React.Component {
   constructor(props) {
      super(props);
      this.state = { data: null };
   }   
   componentDidMount() {
      // Try to parse invalid JSON to evoke an error.
      try {
         JSON.parse("This is not valid JSON");
      } catch (error) {
         throw new Error("Something went wrong in MyComponent!");
      }
   }   
   render() {
      
      // Render the component as usual
      return <div>{this.state.data}</div>;
   }
}
class ErrorBoundary extends React.Component {
   constructor(props) {
      super(props);
      this.state = { hasError: false, error: null };
   }
   
   static getDerivedStateFromError(error) {
      
      // Update state to show a fallback UI and store the error
      return { hasError: true, error };
   }   
   componentDidCatch(error, info) {
      console.error("Error caught by ErrorBoundary:", error);
      console.error("Component Stack:", info.componentStack);
   }   
   render() {
   if (this.state.hasError) {
      
      // Render a custom fallback UI with the error message
      return (
         <div>
            <h2>Something went wrong</h2>
            <p>{this.state.error.message}</p>
         </div>
      );
   }
   
   // Render the child components if no error found
   return this.props.children;
   }
}
function App() {
   return (
      <div>
         <h1>My App</h1>
         <ErrorBoundary>
         <MyComponent />
         </ErrorBoundary>
      </div>
   );
}

export default App;

輸出

my app

示例 - 帶有錯誤處理的動態表單

此應用顯示了一個動態表單,使用者可以在其中將資料輸入欄位。如果在表單資料處理期間發生錯誤,componentDidCatch 方法將記錄錯誤並告知使用者該問題。

import React, { Component } from 'react';

class DynamicForm extends Component {
   constructor(props) {
      super(props);
      this.state = {
         formData: {},
         hasError: false,
      };
   }   
   handleInputChange = (field, value) => {
      try {
         // Logic to handle dynamic form data
         this.setState(prevState => ({
            formData: {
               ...prevState.formData,
               [field]: value,
            },
         }));
      } catch (error) {
         // Handle errors
         this.setState({ hasError: true });
      }
   };   
   handleButtonClick = () => {
      
      // Sending form data to a server
      try {
         
         // Logic to send data to the server
         console.log('Sending form data:', this.state.formData);
      } catch (error) {
         
         // Handle errors in sending data
         console.error('Error sending form data:', error);
         this.setState({ hasError: true });
      }
   };   
   componentDidCatch(error, info) {
      console.error('Form Error:', error, info);
      this.setState({ hasError: true });
   }   
   render() {
      if (this.state.hasError) {
         return <div>Sorry, there was an issue with the form.</div>;
      }
      
      return (
         <div>
            <h1>Dynamic Form</h1>
            <input
               type="text"
               placeholder="Field 1"
               onChange={e => this.handleInputChange('field1', e.target.value)}
            />
            <input
               type="text"
               placeholder="Field 2"
               onChange={e => this.handleInputChange('field2', e.target.value)}
            />
            <button onClick={this.handleButtonClick}>Send Data</button>
         </div>
      );
   }
}

export default DynamicForm;

輸出

dynamic form

當用戶點選“傳送資料”按鈕時,表單資料將記錄到控制檯。我們可以用我們傳送資料到伺服器的實際邏輯替換 handleButtonClick 方法中的 console.log 語句,使用 fetch。

註釋

  • 過去,開發人員在 componentDidCatch 內部使用 setState 來更改使用者介面並顯示錯誤警告。這種方法現在被認為已過時。為了處理錯誤,最好使用 static getDerivedStateFromError。

  • 在開發和生產環境中,React 的行為有所不同。在開發環境中,componentDidCatch 將捕獲錯誤並將它們傳送到瀏覽器的全域性錯誤處理程式。它們不會在生產環境中冒泡,因此我們必須使用 componentDidCatch 顯式捕獲它們。

總結

componentDidCatch 是一個有用的 React 功能,它使我們能夠正確地管理元件中的錯誤。它就像一個安全網,記錄錯誤並允許我們記錄它們或顯示錯誤訊息。請記住,它應該與 getDerivedStateFromError 結合使用,並且開發和生產設定之間存在差異。

reactjs_reference_api.htm
廣告

© . All rights reserved.