在React函数组件中使用错误边界和errorElement进行错误处理

发布于:2024-04-25 ⋅ 阅读:(30) ⋅ 点赞:(0)

在这里插入图片描述

在React 18中,函数组件可以使用两种方式来处理错误:

  1. 使用 ErrorBoundary

ErrorBoundary 是一种基于类的组件,可以捕获其子组件树中的任何 JavaScript 错误,并记录这些错误、渲染备用 UI 而不是冻结的组件树。

在函数组件中使用 ErrorBoundary,需要先创建一个基于类的 ErrorBoundary 组件,然后将函数组件包裹在其中:

import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 你同样可以将错误记录到一个错误报告服务器
    console.log(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

function MyFunctionComponent() {
  // ...
}

// 使用 ErrorBoundary 包裹函数组件
const WrappedComponent = () => (
  <ErrorBoundary>
    <MyFunctionComponent />
  </ErrorBoundary>
);
  1. 使用 errorElement 属性 (React 18)

在 React 18 中,你可以在根组件上使用 errorElement 属性来指定发生错误时要渲染的 UI。这个属性可以直接在函数组件上使用:

import React from 'react';

function ErrorUI() {
  return <h1>Something went wrong.</h1>;
}

function MyFunctionComponent() {
  // ...
  return (
    <>
      {/* 组件树 */}
      {errorElement && <ErrorUI />}
    </>
  );
}

// 在根组件上使用 errorElement
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <MyFunctionComponent errorElement={<ErrorUI />} />
  </React.StrictMode>
);

在上面的示例中,如果在 MyFunctionComponent 组件树中发生错误,React 会自动卸载组件树,并替换为传递给 errorElement 属性的 UI。

注意,errorElement 只适用于根组件。如果需要为嵌套的组件树提供错误边界,你仍然需要使用 ErrorBoundary 组件。

总的来说,ErrorBoundary 是一种更通用的错误处理方式,可用于任何组件及其子组件树。而 errorElement 提供了一种更简单的方式来处理根组件中的错误。你可以根据项目的需求选择合适的方式。