react 的 错误边界 是一个 class 组件
- 作用:捕获并打印发生在其子组件树任何位置的 JavaScript 错误,并且,它会渲染出备用 UI,而不是渲染那些崩溃了的子组件树。
- 使用:如果一个 class 组件中定义了 static getDerivedStateFromError() 或 componentDidCatch() 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界。
- 案例
import React, { Component } from 'react'
type FallbackRender = (props: {error: Error | null }) => React.ReactElement;
export class ErrorBoundary extends React.Component<React.PropsWithChildren<{ fallbackRender: FallbackRender }>, any>{
state = {
error: null
}
static getDerivedStateFromError(error: Error){
return { error }
}
render(){
const { error } = this.state;
const { fallbackRender, children } = this.props;
if(error){
return fallbackRender(error);
}
return children;
}
}
<ErrorBoundary fallbackRender={}>
<App />
</ErrorBoundary>