日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React?錯誤邊界Error?Boundary使用示例解析_React

作者:凌辰亦夢 ? 更新時間: 2022-11-09 編程語言

我們為什么需要錯誤邊界

在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

欄目分類
最近更新