reactjs React错误边界未捕获错误

xhv8bpkk  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(132)

我从vite创建了我的react应用程序,并从组件中 Package 了我的自定义React错误边界组件,问题是它无法捕获错误。我调试了我的错误组件,但它无法接收getDerivedStateFromError中的任何值,而不是componentDidCatch中的任何值
下面是我的错误边界代码:

/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { Component } from 'react';

interface IState {
  hasError: boolean;
  eventId?: string;
}

// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface IProps {
  children: any;
}

export default class ErrorBoundary extends Component<IProps, IState> {
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = { eventId: '', hasError: false };
  }

  static getDerivedStateFromError(error: any) {
    console.log('here get Derived');
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

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

  render() {
    // const { children } = this.props;
    console.log('errors');
    if (this.state.hasError) {
      console.log('errors found', this.state.hasError);
      return (
        <button
          onClick={() =>
            console.log("Error Found)
          }
        >
          Report feedback
        </button>
      );
    }

    return this.props.children;
  }
}

和我的app.js代码:

import './App.css';
function App() {

  return (
    <div className="App">
      <header className="App-header">
        <ErrorBoundary>
          <button
            onClick={() => {
              throw new Error('Im new Error');
            }}
          >
            Click Me
          </button>
        </ErrorBoundary>
      </header>
    </div>
  );
}

export default App;

有没有人知道问题是甚么?

oxf4rvwz

oxf4rvwz1#

错误边界不捕获以下对象的错误:

  • 事件行程常式
  • 异步代码(例如setTimeout或requestAnimationFrame回调)
  • 服务器端渲染
  • 在错误边界本身(而不是其子级)中引发的错误

https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries
要模拟错误,您需要创建一个组件,使其成为ErrorBoundary类的子级,然后单击按钮2次

function Button() {
    
      const [count, setCount] = useState(0);
      const onClick = () => {
        setCount(count + 1);
      };
      useEffect(() => {
        if (count === 2) {
          throw new Error('I crashed!');
        }
      });
        
      return (
          <button
              onClick={onClick}
           >
              Click Me
           </button>
       );
    }
        
    export default Button;

相关问题