Skip to content

错误边界

什么是错误边界

错误边界用于 React 中捕获子组件树中发生的 JavaScript 错误,并输出这些错误,防止整个应用崩溃。

错误边界可以捕获渲染期间、生命周期方法以及其下整个树的构造函数中发生的错误。

使用类式错误边界组件

tsx
import { Component } from "react";

export class CustomErrorBoundary extends Component {
  constructor(props: any) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error: any, errorInfo: any) {
    console.log(error, errorInfo);
  }

  render() {
    if ((this.state as any).hasError) {
      return <p>something went wrong.</p>;
    }

    return (this.props as any).children;
  }
}
tsx
import { CustomErrorBoundary } from "./CustomErrorBoundary";

function BuggyComponent({ isError }: { isError: boolean }) {
  if (isError) throw new Error("I crashed during rendering!");

  return <div>这个组件将不会被渲染。</div>;
}

export default function CustomErrorBoundaryDemo() {
  return (
    <CustomErrorBoundary>
      <BuggyComponent isError />
    </CustomErrorBoundary>
  );
}

使用函数式错误边界组件

目前还无法将错误边界编写为函数式组件,但是可以借助第三方库(react-error-boundary)来实现。

bash
# npm
npm install react-error-boundary

# pnpm
pnpm add react-error-boundary

# yarn
yarn add react-error-boundary
tsx
import { ErrorBoundary } from "react-error-boundary";

function BuggyComponent({ isError }: { isError: boolean }) {
  if (isError) throw new Error("I crashed during rendering!");

  return <div>这个组件将不会被渲染。</div>;
}

export default function ReactErrorBoundary() {
  return (
    <>
      <ErrorBoundary fallback={<div>something went wrong!</div>}>
        <BuggyComponent isError />
      </ErrorBoundary>
    </>
  );
}