javascript - 使用到达路由器导航到 404 路由

标签 javascript reactjs routes http-status-code-404 reach-router

我有以下路由配置:

<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/

相关文章:

javascript - 防止固定 Div 覆盖其他 Div

javascript - 使用 waitForSelector 方法在 Puppeteer JS 中更改类名时获取元素

javascript - 为什么 JS 允许在数组中使用负索引?

CSS 模块覆盖 UI 样式

javascript - 在对象数组的 react setState 中使用扩展运算符

javascript - 根据可选路线的不同查询 -expressjs

javascript - 如何正确地从数据库中获取信息?

javascript - 数组上的 redux reducer 扩展运算符不替换旧状态

asp.net-mvc - 带有自定义文字的 asp .net mvc 路由 url

cakephp - 路由: 'admin' => true vs 'prefix' => 'admin in CakePHP