反应:使用错误边界来突出显示损坏的组件



我正在使用 React 16.3,它通过ComponentDidCatch()函数覆盖支持错误边界。我也在使用打字稿。

为了便于将来调试,我想以某种方式捕获组件级别的任何错误/异常,以便在 UI 中突出显示(绘制黄色方块(以指示损坏组件的位置。

我怎样才能做到这一点,而不必在我使用的每个组件周围显式声明错误边界?

也许可以在构建时包装它们?我还假设错误边界需要以某种方式从损坏的组件中获取道具,以便知道在哪里绘制黄色方块。我怎样才能做到这一点?

我对 React 很陌生,所以提前感谢。

我认为如果您想使用错误边界,请在 dom 渲染中使用它。

import * as ReactDOM from 'react-dom';
import {ErrorBoundary} from 'your-path';
ReactDOM.render(
<ErrorBoundary>
//Router or other stuff
</ErrorBoundary>,
document.getElementById('root') as HTMLElement
);

创建这样的ErrorBoundary组件。

import * as React from 'react';
interface IErrorBoundaryState {
isError: boolean;
error: React.ErrorInfo;
}
export class ErrorBoundary extends React.Component<{}, IErrorBoundaryState> {
this.state = {isError: false, error: null};
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
this.setState({ isError: true, error: errorInfo });
}
render(): any {
if (this.state.isError) {
return <div>{this.state.error.componentStack}</div>;
}
return this.props.children;
}
}

最新更新