React?錯誤邊界Error?Boundary使用示例解析
我們?yōu)槭裁葱枰e誤邊界
在React組件中可能會由于某些JavaScript錯誤,導致一些無法追蹤的錯誤,導致應用崩潰。部分 UI 的 JavaScript 錯誤不應該導致整個應用崩潰。為此,React引入了錯誤邊界(Error Boundary)的概念:可以捕獲發(fā)生在其子組件樹任何位置的 JavaScript 錯誤,并打印這些錯誤,同時展示降級 UI,而并不會渲染那些發(fā)生崩潰的子組件樹。
而在React16以后,未捕獲的錯誤會導致React組件樹的卸載,也就是白屏。所以某些情況下還是非常需要使用Error Boundary組件來避免這種比較嚴重的問題。
如何使用錯誤邊界組件
按照React官方的約定,一個類組件定義了static getDerivedStateFromError() 或componentDidCatch() 這兩個生命周期函數(shù)中的任意一個(或兩個),即可被稱作ErrorBoundary組件,實現(xiàn)錯誤邊界的功能。
其中,getDerivedStateFromError方法被約定為渲染備用UI,componentDidCatch方法被約定為捕獲打印錯誤信息。
具體的實現(xiàn)如下:
//ErrorBoundary.tsx
import * as React from 'react';
interface PropsType {
children: React.ReactNode;
}
interface StateType {
hasError: boolean,
Error?: null | Error,
ErrorInfo?: null | React.ErrorInfo,
}
export class ErrorBoundary extends React.Component<PropsType, StateType> {
constructor(props: PropsType) {
super(props);
this.state = {
hasError: false,
Error: null,
ErrorInfo: null
};
}
//控制渲染降級UI
static getDerivedStateFromError(error: Error): StateType {
return {hasError: true};
}
//捕獲拋出異常
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
//傳遞異常信息
this.setState((preState) =>
({hasError: preState.hasError, Error: error, ErrorInfo: errorInfo})
);
//可以將異常信息拋出給日志系統(tǒng)等等
//do something....
}
render() {
//如果捕獲到異常,渲染降級UI
if (this.state.hasError) {
return <div>
<h1>{`Error:${this.state.Error?.message}`}</h1>
<details style={{whiteSpace: 'pre-wrap'}}>
{this.state.ErrorInfo?.componentStack}
</details>
</div>;
}
return this.props.children;
}
}
實現(xiàn)ErrorBoundary組件后,我們只需要將其當作常規(guī)組件使用,將其需要捕獲的組件放入其中即可。
使用方式如下:
//main.tsx
import ReactDOM from 'react-dom/client';
import {ErrorBoundary} from './ErrorBoundary.jsx';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<ErrorBoundary>
<App/>
</ErrorBoundary>
);
//app.tsx
import * as React from 'react';
function App() {
const [count, setCount] = useState(0);
if (count>0){
throw new Error('count>0!');
}
return (
<div>
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
</div>
);
}
export default App;
點擊按鈕后即可展示拋出異常時,應該渲染的降級UI:

使用錯誤邊界需要注意什么
沒有什么技術棧或者技術思維是銀彈,錯誤邊界看起來用得很爽,但是需要注意以下幾點:
- 錯誤邊界實際上是用來捕獲render階段時拋出的異常,而React事件處理器中的錯誤并不會渲染過程中被觸發(fā),所以錯誤邊界捕獲不到事件處理器中的錯誤。
- React官方推薦使用try/catch來自行處理事件處理器中的異常。
- 錯誤邊界無法捕獲異步代碼中的錯誤(例如
setTimeout或requestAnimationFrame回調函數(shù)),這兩個函數(shù)中的代碼通常不在當前任務隊列內執(zhí)行。 - 目前錯誤邊界只能在類組件中實現(xiàn),也只能捕獲其子組件樹的錯誤信息。錯誤邊界無法捕獲自身的錯誤,如果一個錯誤邊界無法渲染錯誤信息,則錯誤會冒泡至最近的上層錯誤邊界,類似于JavaScript中的cantch的工作機制。
- 錯誤邊界無法在服務端渲染中生效,因為根本的渲染方法已經(jīng)
ReactDOM.createRoot().render()修改為了ReactDOM.hydrateRoot(), 而上面也提到了,錯誤邊界捕獲的是render階段時拋出的異常。
以上就是React 錯誤邊界Error Boundary使用示例解析的詳細內容,更多關于React 錯誤邊界的資料請關注腳本之家其它相關文章!
相關文章
React-Native做一個文本輸入框組件的實現(xiàn)代碼
這篇文章主要介紹了React-Native做一個文本輸入框組件的實現(xiàn)代碼,非常具有實用價值,需要的朋友可以參考下2017-08-08

