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

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

  1. 使用 ErrorBoundary

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

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

js 复制代码
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。这个属性可以直接在函数组件上使用:

js 复制代码
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 提供了一种更简单的方式来处理根组件中的错误。你可以根据项目的需求选择合适的方式。

相关推荐
console.log('npc')2 天前
Cursor,Trae,Claude Code如何协作生产出一套前后台app?
前端·人工智能·react.js·设计模式·ai·langchain·ai编程
Coding张2 天前
React 底层运行原理框架(大白话版)
react.js
Csvn2 天前
React 渲染机制详解
react.js
弓.长.2 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-masked-view — 遮罩视图组件
react native·react.js·harmonyos
大雷神2 天前
HarmonyOS APP<玩转React>开源教程十四:进度管理服务
前端·react.js·开源·harmonyos
早點睡3902 天前
ReactNative项目OpenHarmony三方库集成实战:react-native-image-crop-picker
javascript·react native·react.js
早點睡3902 天前
ReactNative项目OpenHarmony三方库集成实战:react-native-image-gallery
javascript·react native·react.js
console.log('npc')2 天前
git代码冲突reset,如何回退到冲突之前提交之前的版本
javascript·git·react.js
早點睡3902 天前
ReactNative项目OpenHarmony三方库集成实战:@react-native-community/geolocation
javascript·react native·react.js
im_AMBER2 天前
前后端对接: ESM配置与React Router
前端·javascript·学习·react.js·性能优化·前端框架·ecmascript