使用 Reach 路由器导航到 404 路由

Und*_*ion 5 javascript routes http-status-code-404 reactjs reach-router

我有以下路由配置:

<Router>
 <NotFound default />
 <ResourcesContainer path="/resources" />
 <ResourceContainer path="/resources/:id" />
 ...
</Router>
Run Code Online (Sandbox Code Playgroud)

这会捕获任何未处理的路由,并<NotFound />在未找到的 URL 处呈现组件,因此如果我键入example.com/blah,我会看到<NotFound />呈现的组件,并且在地址栏中会看到example.com/blah。我还在页面上使用此 URL 来显示消息:

找不到页面“example/blah”。

到目前为止,一切都很好。但是我还需要从/resources/*路由内部处理 404。我的<ResourcesContainer/>组件使用路径的最后一部分来访问具有该 id 的资源的 GraphQL API。如果 API 返回告诉客户端资源不存在,我想模仿上面概述的行为。但是,我没有可以导航到的页面。我可以复制该<NotFound />路线并给它一个明确path/404,然后导航到该路线。然而,URL 将是/404,而不是resources/*未找到的原始路径。

以下解决了部分问题,给了我一个重定向 ot 的页面,但意味着/404在所有情况下 URL 都会被重写:

<Router>
 <ResourcesContainer path="/resources" />
 <ResourceContainer path="/resources/:id" />
 <NotFound path="/404" />
 <Redirect noThrow from="*" to="/404" />
 ...
</Router>
Run Code Online (Sandbox Code Playgroud)

我该如何设置才能在不丢失原始 URL 的情况下navigate访问该路由?<NotFound />

Gök*_*urt 3

如果找不到资源,最好的选择是更改渲染方法以ResourceContainer进行渲染。NotFound

但是,如果您不想更改ResourceContainer,可以使用错误边界将其包裹起来,如下所示:

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; 
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<NotFoundErrorBoundary>
 <ResourceContainer path="/resources/:id" />
</NotFoundErrorBoundary>
Run Code Online (Sandbox Code Playgroud)

ResourceContainer可以抛出一个可以识别的错误NotFoundErrorBoundary,这可以表明未找到资源,并且它应该呈现NotFound页面而不是子项。

需要明确的是,我并不鼓励您使用 ErrorBoundary。在我看来,这会让事情变得过于复杂。我只是向您提供信息,您如何使用它取决于您。此外,根据用例,它在其他上下文中可能对您有用。