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

Redirect to error page ReactJS and react-router

我试图在应用程序中断时将用户发送到一般错误页面,我正在尝试使用 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 永远不会被触发,因此永远不会离开当前错误页面,无论是开发版本还是生产版本。当应用程序中断或试图抛出错误时,如何将用户发送到 X 路由?

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

componentDidCatch 仅当 errorrenderthrown 时触发方法。

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

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

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

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

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

React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces. Now you can see where exactly in the component tree the failure has happened: