【发布时间】: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