为什么即使我使用错误边界,我的 React 应用程序也会崩溃?

mor*_*eza 3 reactjs

我正在尝试学习如何在 React js 中使用错误边界。正如我在这里读到的那样它可以防止您的应用程序崩溃。但是我的应用程序崩溃了!这是我的代码:

应用组件:

function App() {
  return (
    <>
      <h1>app component</h1>
      <ErrorBoundary >
        <Simple />
      </ErrorBoundary>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

简单组件:

export default () => {
    throw new Error('I crashed!')
    return <h3> simple component</h3>
}
Run Code Online (Sandbox Code Playgroud)

这是我的边界=

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

    static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        console.log("I got you ")
        return { hasError: true };

    }

    componentDidCatch(error, errorInfo) {
        // You can also log the error to an error reporting service
        console.log(error, errorInfo);


    }

    render() {
        if (this.state.hasError) {
            // You can render any custom fallback UI
            return <h1>Something went wrong.</h1>;
        }

        return this.props.children;
    }
}
export default ErrorBoundary;
Run Code Online (Sandbox Code Playgroud)

在很短的时间内,我看到消息“出了点问题”,但在那之后页面崩溃了!

感谢您的帮助和建议

Nik*_*yal 5

如果应用程序在开发环境中崩溃,这是预期行为,以便开发人员可以解决问题。

ErrorBoundaries 应该只在生产环境中工作而不会崩溃。

  • 谢谢 Nikhili,你是对的,我刚刚在生产模式下尝试过,它有效!我想知道为什么文档没有提到它! (2认同)
  • 为什么?我不明白这其中的逻辑。我的意思是,开发人员当然应该修复它。但是开发人员可以轻松修复它,即使错误边界有效,您仍然会收到错误。那么为什么要破坏应用程序呢?它只会让测试变得更加困难。 (2认同)