【问题标题】:Redirect to error page ReactJS and react-router重定向到错误页面 ReactJS 和 react-router
【发布时间】:2018-09-13 08:23:51
【问题描述】:

当应用程序中断时,我试图将用户发送到通用错误页面,我正在尝试使用 ErrorBoundary 方法,然后呈现重定向;

export default class ErrorBoundary extends Component {
    state = { has_error: false }

    componentDidCatch(error, info)
        this.setState({ has_error: true });
    }


    render() {
        if (this.state.has_error)
            return <Redirect to="/somewhere/else" />
        }
        return this.props.children;
    }
};

然后使用ErrorBoundary将Router内部的所有路由和子组件包裹起来

<Router history={history}>
    <ErrorBoundary>
        <Header />
        <Switch>
            <Route exact path="/" component={Home} />
            <Route
                path="/createManager/:managerId"
                component={CreateManager}
            />
            <Route path="/login" component={LoginComp} />
            <Route path="/test" component={Test} />
            <Route path="/register" component={RegisterAccount} />
            <Route component={NotFound} />
        </Switch>
        <Footer />
    </ErrorBoundary>
</Router>

componentDidCatch 永远不会被触发,因此永远不会离开当前的错误页面,无论是在 dev 还是 prod 版本中。当应用程序中断或尝试抛出错误时,如何将用户发送到 X 路由?

为了触发错误,我给一个组件留了一个空的 prop,然后点击尝试使用应该在 prop 中传递的函数。

【问题讨论】:

  • 究竟是什么不起作用?
  • componentDidCatch 永远不会被触发,因此永远不会离开当前的错误页面
  • 你在哪里定义了ErrorBoundary组件
  • 你能分享一下引发错误的代码吗?
  • 对不起,做了一个小编辑,因为我从另一个组件复制粘贴了我保留了类名,但它不影响因为它是默认导出并且在路由器 comp 中导入时给出了中殿import ErrorBoundary from "./ErrorBoundary";

标签: javascript reactjs ecmascript-6 react-router react-dom


【解决方案1】:

componentDidCatch 仅在 render 方法内抛出 错误 时触发。

您的componentDidCatch 没有被触发的原因是因为像onClick 这样的事件 不在render 生命周期中。所以componentDidCatch 将无法捕捉到这种错误。

测试componentDidCatch 的一种方法是在render 方法中抛出错误。

对于渲染方法之外的错误,您必须小心,并在您认为在您的操作处理程序中可能有错误的地方添加 try/catch。

另外一个防止未定义 onClick 的好方法是添加 flowtypescript

https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html#component-stack-traces

React 16 将 rendering 期间发生的所有错误打印到开发中的控制台,即使应用程序不小心吞下了它们。除了错误消息和 JavaScript 堆栈之外,它还提供组件堆栈跟踪。现在您可以看到失败发生在组件树中的确切位置:

【讨论】:

  • 完全正确。但是没有代码很难猜到这是问题所在。
猜你喜欢
  • 2018-11-27
  • 2022-06-30
  • 2021-08-24
  • 2019-02-05
  • 2022-01-22
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 2017-11-23
相关资源
最近更新 更多