注意點:
- 類組件是可以和函數式組件混合寫的!!!
- getDerivedStateFromError是靜態的,避免副作用,如果想將錯誤上報到服務器,則去
componentDidCatch
里去處理。 - getDerivedStateFromError直接返回
{ hasError: true, errorInfo: error }
,即可修改當前錯誤邊界組件的 state,從而達到控制顯示內容的效果。 - 錯誤邊界不捕捉以下錯誤。
- 事件處理程序(了解更多
- 異步代碼(例如 setTimeout 或 requestAnimationFrame 回調)。
- 服務器端的渲染
- 在錯誤邊界本身(而不是其子女)中拋出的錯誤
import { Store } from 'antd/es/form/interface';
import React from 'react';function Bomb({ username }) {console.log('username', username);if (username === 'bomb') {throw new Error('💥 CABOOM 💥');}return <div>{`Hi ${username}`}</div>;
}import { Component } from 'react';class MyErrorBoundary extends Component {constructor(props: any) {super(props);this.state = {hasError: false,errorInfo: null,};}componentDidMount(): void {console.log('this.props', this.props);}componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {// 在這里可以做錯誤收集、打印、掉接口上報console.log('MyErrorBoundary _________ componentDidCatch error,errorInfo',error,errorInfo,);}static getDerivedStateFromError(error: Error) {console.log('MyErrorBoundary _________ getDerivedStateFromError error,errorInfo', error);return { hasError: true, errorInfo: error };}render() {const { hasError, errorInfo } = this.state;return (<div style={{ border: '2px solid pink' }}>這里是我自定義的錯誤邊界{hasError ? (<div><h2>Something went wrong!!!!!</h2><pre style={{ color: 'pink' }}>{errorInfo.message}</pre></div>) : (this.props.children)}</div>);}
}function App() {const [username, setUsername] = React.useState('');const usernameRef = React.useRef(null);return (<div><label>{`Username (don't type "bomb"): `}<inputplaceholder={`type "bomb"`}value={username}onChange={(e) => setUsername(e.target.value)}ref={usernameRef}/></label><div><MyErrorBoundary><Bomb username={username} /></MyErrorBoundary></div></div>);
}export default App;