3

我有一个组件故意抛出错误,包裹在错误边界组件中。

它捕获错误并显示消息,但仅显示一瞬间。

这是我的包装组件

  useEffect(() => {   
        error(); 
    }, []);

    const error = () => {
        try {
            return [].replace(/'--'/, '')
        } catch (error) {
           throw(error)
            
        }
    }

和我的错误边界组件

class ErrorBoundary extends Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
  
    static getDerivedStateFromError(error) {
        console.log('derived', error)
      // Update state so the next render will show the fallback UI.
      return { hasError: true };
    }
  
    componentDidCatch(error, errorInfo) {
        console.log('error did catch', error)
      this.setState({ hasError: true})
    }
  
    render() {
      if (this.state.hasError) {
        return (
            <h1>Something went wrong.</h1>
        );
      }
  
      return this.props.children; 
    }
  }

然后我像这样声明组件

<ErrorBoundary>
   <ProfileContainer />
</ErrorBoundary>

当我的组件加载时,它会按应有的方式捕获错误,并在边界组件中接收它。它显示错误消息,但随后立即崩溃

enter image description here

我处理这个错误的方式吗?我知道错误边界是针对 DOM 错误的,但有趣的是它正在捕获错误。

非常感谢任何帮助

4

1 回答 1

5

This is intentional. Error boundaries are primarily useful for production, but in development, react wants to make errors as highly visible as possible (so the stack trace appears no matter what).

In production mode, your site will show only the error boundary UI.

于 2021-01-04T19:34:39.010 回答