- ReactJS 教程
- ReactJS - 首頁
- ReactJS - 簡介
- ReactJS - 路線圖
- ReactJS - 安裝
- ReactJS - 特性
- ReactJS - 優點與缺點
- ReactJS - 架構
- ReactJS - 建立 React 應用
- ReactJS - JSX
- ReactJS - 元件
- ReactJS - 巢狀元件
- ReactJS - 使用新建立的元件
- ReactJS - 元件集合
- ReactJS - 樣式
- ReactJS - 屬性 (props)
- ReactJS - 使用屬性建立元件
- ReactJS - props 驗證
- ReactJS - 建構函式
- ReactJS - 元件生命週期
- ReactJS - 事件管理
- ReactJS - 建立一個事件感知元件
- ReactJS - 在 Expense Manager 應用中引入事件
- ReactJS - 狀態管理
- ReactJS - 狀態管理 API
- ReactJS - 無狀態元件
- ReactJS - 使用 React Hooks 進行狀態管理
- ReactJS - 使用 React Hooks 的元件生命週期
- ReactJS - 佈局元件
- ReactJS - 分頁
- ReactJS - Material UI
- ReactJS - Http 客戶端程式設計
- ReactJS - 表單程式設計
- ReactJS - 受控元件
- ReactJS - 非受控元件
- ReactJS - Formik
- ReactJS - 條件渲染
- ReactJS - 列表
- ReactJS - Keys
- ReactJS - 路由
- ReactJS - Redux
- ReactJS - 動畫
- ReactJS - Bootstrap
- ReactJS - 地圖
- ReactJS - 表格
- ReactJS - 使用 Flux 管理狀態
- ReactJS - 測試
- ReactJS - CLI 命令
- ReactJS - 構建和部署
- ReactJS - 示例
- Hooks
- ReactJS - Hooks 簡介
- ReactJS - 使用 useState
- ReactJS - 使用 useEffect
- ReactJS - 使用 useContext
- ReactJS - 使用 useRef
- ReactJS - 使用 useReducer
- ReactJS - 使用 useCallback
- ReactJS - 使用 useMemo
- ReactJS - 自定義 Hooks
- ReactJS 高階
- ReactJS - 可訪問性
- ReactJS - 程式碼分割
- ReactJS - Context
- ReactJS - 錯誤邊界
- ReactJS - 轉發 Refs
- ReactJS - 碎片
- ReactJS - 高階元件
- ReactJS - 與其他庫整合
- ReactJS - 最佳化效能
- ReactJS - Profiler API
- ReactJS - 埠
- ReactJS - 無 ES6 ECMAScript 的 React
- ReactJS - 無 JSX 的 React
- ReactJS - 調和
- ReactJS - Refs 和 DOM
- ReactJS - 渲染 Props
- ReactJS - 靜態型別檢查
- ReactJS - 嚴格模式
- ReactJS - Web Components
- 其他概念
- ReactJS - 日期選擇器
- ReactJS - Helmet
- ReactJS - 內聯樣式
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - 輪播圖
- ReactJS - 圖示
- ReactJS - 表單元件
- ReactJS - 參考 API
- ReactJS 有用資源
- ReactJS - 快速指南
- ReactJS - 有用資源
- ReactJS - 討論
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;
輸出
示例 - 帶有錯誤處理的動態表單
此應用顯示了一個動態表單,使用者可以在其中將資料輸入欄位。如果在表單資料處理期間發生錯誤,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;
輸出
當用戶點選“傳送資料”按鈕時,表單資料將記錄到控制檯。我們可以用我們傳送資料到伺服器的實際邏輯替換 handleButtonClick 方法中的 console.log 語句,使用 fetch。
註釋
過去,開發人員在 componentDidCatch 內部使用 setState 來更改使用者介面並顯示錯誤警告。這種方法現在被認為已過時。為了處理錯誤,最好使用 static getDerivedStateFromError。
在開發和生產環境中,React 的行為有所不同。在開發環境中,componentDidCatch 將捕獲錯誤並將它們傳送到瀏覽器的全域性錯誤處理程式。它們不會在生產環境中冒泡,因此我們必須使用 componentDidCatch 顯式捕獲它們。
總結
componentDidCatch 是一個有用的 React 功能,它使我們能夠正確地管理元件中的錯誤。它就像一個安全網,記錄錯誤並允許我們記錄它們或顯示錯誤訊息。請記住,它應該與 getDerivedStateFromError 結合使用,並且開發和生產設定之間存在差異。