跳至主要内容

错误边界

选项 1:使用 react-error-boundary

React-error-boundary - 是一个轻量级的包,可用于此场景,并内置了 TS 支持。此方法还可以避免不再流行的类组件。

选项 2:编写自定义错误边界组件

如果您不想为此添加新的 npm 包,您也可以编写自己的 ErrorBoundary 组件。

import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
children?: ReactNode;
}

interface State {
hasError: boolean;
}

class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false
};

public static getDerivedStateFromError(_: Error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}

public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error("Uncaught error:", error, errorInfo);
}

public render() {
if (this.state.hasError) {
return <h1>Sorry.. there was an error</h1>;
}

return this.props.children;
}
}

export default ErrorBoundary;

有需要补充的吗?提交问题.