重定向到错误页面ReactJS和react-router

Nic*_*rdo 5 javascript ecmascript-6 reactjs react-router react-dom

当应用程序中断时,我试图将用户发送到通用错误页面,我正在尝试使用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;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后使用ErrorBoundary将所有路由和子组件包装在路由器内部

<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>
Run Code Online (Sandbox Code Playgroud)

永远不会触发componentDidCatch,因此,无论是在开发版还是产品版中,都永远不会离开当前错误页面。当应用中断或尝试引发错误时,如何将用户发送到X路由?

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

Ken*_*ong 5

componentDidCatch只有当触发错误抛出内部渲染方法。

之所以componentDidCatch不会触发您,是因为类似这样的事件onClick不在render生命周期中。因此componentDidCatch将无法捕获此类错误。

一种测试您componentDidCatchrender方法是在方法内部抛出错误。

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

防止未定义onClick的一种好方法是添加flowtypescript

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

rendering即使应用程序意外吞噬了它们,React 16 也会将开发过程中发生的所有错误打印到控制台。除了错误消息和JavaScript堆栈外,它还提供组件堆栈跟踪。现在您可以看到故障在组件树中的确切位置: