我有以下路由配置:
<Router>
<NotFound default />
<ResourcesContainer path="/resources" />
<ResourceContainer path="/resources/:id" />
...
</Router>
这会捕获任何未处理的路由,并呈现 <NotFound />
未找到的 URL 中的组件,所以如果我输入 example.com/blah
,我看到了<NotFound />
渲染组件,在地址栏中我看到 example.com/blah
.我还在页面上使用此 URL 来显示一条消息:The page 'example/blah' was not found.
到目前为止,一切都很好。但是,我还需要在
/resources/*
中处理 404。路线。我的 <ResourcesContainer/>
组件使用路径的最后一部分为具有该 id 的资源访问 GraphQL API。如果 API 返回告诉客户端资源不存在,我想模仿上面概述的行为。但是,我没有指向 navigate 的页面至。我可以复制 <NotFound />
路由并给它一个明确的path
的 /404
,然后导航到那个。但是 URL 将是 /404
而不是原来的resources/*
找不到的路径。以下解决了部分问题,给了我一个重定向的页面,但是意味着URL被重写为
/404
在所有情况下:<Router>
<ResourcesContainer path="/resources" />
<ResourceContainer path="/resources/:id" />
<NotFound path="/404" />
<Redirect noThrow from="*" to="/404" />
...
</Router>
如何设置它以便我可以 navigate
到<NotFound />
在不丢失原始 URL 的情况下路由?
最佳答案
您最好的选择是更改 ResourceContainer
的渲染方法渲染 NotFound
如果找不到资源。
但是,如果您不想更改 ResourceContainer
, 你可以用 error boundary 包裹它像这样:
class NotFoundErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { notFound: false };
}
static getDerivedStateFromError(error) {
// Filter which kind of errors you want to show the error boundary for
return { notFound: true };
}
render() {
if (this.state.notFound) {
// You can render any custom fallback UI
return <NotFound />;
}
return this.props.children;
}
}
并像这样使用它:<NotFoundErrorBoundary>
<ResourceContainer path="/resources/:id" />
</NotFoundErrorBoundary>
您的 ResourceContainer
会抛出错误 NotFoundErrorBoundary
可以识别并且可以发出未找到资源的信号并且应该呈现 NotFound
页面而不是 child 。需要明确的是,我不鼓励您使用 ErrorBoundary。在我看来,这会使事情变得过于复杂。我只是向您提供信息,您如何使用它取决于您。根据用例,它在其他情况下也可能对您有用。
关于javascript - 使用到达路由器导航到 404 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65217895/