網站首頁 編程語言 正文
我們為什么需要錯誤邊界
在React組件中可能會由于某些JavaScript錯誤,導致一些無法追蹤的錯誤,導致應用崩潰。部分 UI 的 JavaScript 錯誤不應該導致整個應用崩潰。為此,React引入了錯誤邊界(Error Boundary)的概念:可以捕獲發生在其子組件樹任何位置的 JavaScript 錯誤,并打印這些錯誤,同時展示降級 UI,而并不會渲染那些發生崩潰的子組件樹。
而在React16以后,未捕獲的錯誤會導致React組件樹的卸載,也就是白屏。所以某些情況下還是非常需要使用Error Boundary組件來避免這種比較嚴重的問題。
如何使用錯誤邊界組件
按照React官方的約定,一個類組件定義了static getDerivedStateFromError() 或componentDidCatch() 這兩個生命周期函數中的任意一個(或兩個),即可被稱作ErrorBoundary組件,實現錯誤邊界的功能。
其中,getDerivedStateFromError方法被約定為渲染備用UI,componentDidCatch方法被約定為捕獲打印錯誤信息。
具體的實現如下:
//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}) ); //可以將異常信息拋出給日志系統等等 //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; } }
實現ErrorBoundary組件后,我們只需要將其當作常規組件使用,將其需要捕獲的組件放入其中即可。
使用方式如下:
//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事件處理器中的錯誤并不會渲染過程中被觸發,所以錯誤邊界捕獲不到事件處理器中的錯誤。
- React官方推薦使用try/catch來自行處理事件處理器中的異常。
- 錯誤邊界無法捕獲異步代碼中的錯誤(例如?
setTimeout
或?requestAnimationFrame
回調函數),這兩個函數中的代碼通常不在當前任務隊列內執行。 - 目前錯誤邊界只能在類組件中實現,也只能捕獲其子組件樹的錯誤信息。錯誤邊界無法捕獲自身的錯誤,如果一個錯誤邊界無法渲染錯誤信息,則錯誤會冒泡至最近的上層錯誤邊界,類似于JavaScript中的cantch的工作機制。
- 錯誤邊界無法在服務端渲染中生效,因為根本的渲染方法已經
ReactDOM.createRoot().render()
修改為了ReactDOM.hydrateRoot()
, 而上面也提到了,錯誤邊界捕獲的是render階段時拋出的異常。
原文鏈接:https://juejin.cn/post/7144652395128029192
相關推薦
- 2022-09-15 C#獲取文件名和文件路徑的兩種實現方式_C#教程
- 2023-01-17 Qt中控件的函數使用教程分享_C 語言
- 2022-07-08 Asp.Net?Core7?preview4限流中間件新特性詳解_實用技巧
- 2022-06-30 C++四種case的詳細介紹小結_C 語言
- 2022-07-19 react props的特點
- 2022-09-16 Pandas數據形狀df.shape的實現_python
- 2022-06-22 使用Git向GitHub上傳更新內容_其它綜合
- 2022-11-16 常用的Git便捷操作合集_相關技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支