如果在任何生命周期方法或任何子組件的呈現階段發生一些錯誤,則調用getDerivedStateFromError()方法。此方法用於為React應用程序實現錯誤邊界。在渲染階段調用它,因此該方法不允許使用side-effects。對於side-effects,請改用componentDidCatch()。
用法:
static getDerivedStateFromError(error)
參數:它接受作為參數拋出的錯誤。
創建React應用程序:
步驟1:使用以下命令創建React應用程序:
npx create-react-app foldername
步驟2:建立專案資料夾(即資料夾名稱)之後,使用以下指令移至該資料夾:
cd foldername
示例:程序演示如何使用getDerivedStateFromError()方法。
項目結構:它將如下所示。
文件名:App.js
Javascript
import React, { Component } from 'react';
export default class App extends Component {
// Intializing the state
state = {
error:false
};
static getDerivedStateFromError(error) {
// Changing the state to true if some error occurs
return {
error:true,
};
}
render() {
return (
<React.StrictMode>
<div>
{this.state.error ? <div>Some error</div>:<GFGComponent />}
</div>
</React.StrictMode>
);
}
}
class GFGComponent extends Component {
// GFGComponent throws error as state of GFGCompnonent is not defined
render() {
return <h1>{this.state.heading}</h1>;
}
}
運行應用程序的步驟:從項目的根目錄中使用以下命令運行應用程序:
npm start
輸出:
參考:https://reactjs.org/docs/react-component.html#static-getderivedstatefromerror
相關用法
- ReactJS shouldComponentUpdate()用法及代碼示例
- ReactJS componentDidMount()用法及代碼示例
- ReactJS getSnapshotBeforeUpdate()用法及代碼示例
- ReactJS bind()用法及代碼示例
- ReactJS componentDidUpdate()用法及代碼示例
- ReactJS componentDidCatch()用法及代碼示例
- ReactJS componentWillUnmount()用法及代碼示例
注:本文由純淨天空篩選整理自rbbansal大神的英文原創作品 ReactJS getDerivedStateFromError() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。