【问题标题】:error boundary component catches error but disappears straight away错误边界组件捕获错误但立即消失
【发布时间】:2021-01-04 18:30:01
【问题描述】:

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

它会捕获错误并显示消息,但只显示一秒钟。

这是我的包装组件

  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>

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

我是否以错误的方式处理此问题?我知道错误边界是针对 DOM 错误的,但有趣的是它正在捕获错误。

非常感谢任何帮助

【问题讨论】:

    标签: reactjs try-catch react-error-boundary


    【解决方案1】:

    这是故意的。错误边界主要对生产有用,但在开发中,react 希望使错误尽可能高可见(因此无论如何都会出现堆栈跟踪)。

    在生产模式下,您的网站将仅显示错误边界 UI。

    【讨论】:

    • 谢谢,知道这真的很有用!
    猜你喜欢
    • 2022-09-29
    • 1970-01-01
    • 2020-02-19
    • 2020-06-03
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2020-02-04
    • 2019-11-26
    相关资源
    最近更新 更多