【发布时间】:2021-03-20 21:27:52
【问题描述】:
我有以下路由配置:
<Router>
<NotFound default />
<ResourcesContainer path="/resources" />
<ResourceContainer path="/resources/:id" />
...
</Router>
这会捕获任何未处理的路由,并在未找到的 URL 处呈现 <NotFound /> 组件,因此如果我键入 example.com/blah,我会看到呈现的 <NotFound /> 组件,并且在地址栏中我看到example.com/blah。我也在页面上使用这个 URL 来显示一条消息:
找不到页面'example/blah'。
到目前为止一切顺利。但是,我还需要在 /resources/* 路由中处理 404。我的<ResourcesContainer/> 组件使用路径的最后一部分来访问具有该 ID 的资源的 GraphQL API。如果 API 返回告诉客户端资源不存在,我想模仿上面概述的行为。但是,我没有navigate 的页面。我可以复制<NotFound /> 路由并给它一个明确的path 或/404,然后导航到那个。但是,该 URL 将是 /404,而不是未找到的原始 resources/* 路径。
以下解决了部分问题,给了我一个页面来重定向ot,但意味着URL在所有情况下都被重写为/404:
<Router>
<ResourcesContainer path="/resources" />
<ResourceContainer path="/resources/:id" />
<NotFound path="/404" />
<Redirect noThrow from="*" to="/404" />
...
</Router>
我该如何设置,以便我可以 navigate 到 <NotFound /> 路由而不会丢失原始 URL?
【问题讨论】:
标签: javascript reactjs routes http-status-code-404 reach-router