监听react报错

48 阅读1分钟

什么时候应该使用类组件而不是函数组件?

有一个情况下,你可能还需要使用类组件,React组件错误捕获。

React组件错误捕获怎么做?

封装

import React, { Component } from "react";

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

  static getDerivedStateFromError(error) {
    // 更新状态以显示降级 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 记录错误信息(例如发送到日志服务)
    console.error("Error caught by ErrorBoundary:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 降级 UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

使用

function App() {
  return (
    <ErrorBoundary>
      <MyComponent />
    </ErrorBoundary>
  );
}
注意事项:
  • ErrorBoundaries 只能监听组件渲染报错

  • 生成环境才生效, 开发环境直接抛出错误

  • 无法捕获以下错误:

    • 不会监听dom事件报错
      • 例如click事件中的错误
      • 可以用window.onerror 监听
      • 或者 try catch 监听
    • 异步代码
      • 如 setTimeout 或 Promise中的错误。
      • 异步报错使用window.onerror 监听
    • 服务端渲染中的错误。
    • 错误边界组件自身的错误。