使用 404 未找到页面创建私有路由和 public 路由

Create private route and public route with 404 not found page

我使用 react router v5 制作了一个应用程序路由器。我想在用户转到任何未在路由器中列出的 link 时创建一个 404 未找到页面,无论他们是否登录。

这是我的应用路由器:

<Router>
  <Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/redirect" component={Pages.Redirect} />
    <Route exact path="/login" restricted component={Pages.Login} />
    <Route path="*" component={Pages.NotFound} />
    <Navigation>
      <PrivateRoute exact path="/dashboard" component={Pages.Dashboard} />
      <PrivateRoute exact path="/my-playlist" component={Pages.MyPlaylist} />
      <PrivateRoute exact path="/new-released" component={Pages.NewReleased} />
      <PrivateRoute exact path="/search" component={Pages.CreatePlaylist} />
      <PrivateRoute exact path="/profile" component={Pages.Profile} />
    </Navigation>
  </Switch>
</Router>

问题是,当我转到仪表板、配置文件、搜索等页面时,页面将呈现 404 未找到页面,而不是正确的页面。如果我键入任何 url,页面将呈现 <Navigation> 组件而不是 404 未找到页面。

如何解决?

更新:

现在一切正常。我用 <Navigation> 组件包装了我的私人路由,因此每个私人路由都在 <Navigation>.

内呈现

这是私有路由器:

const PrivateRoute = ({ component: Component, ...rest }: any) => (
  <Navigation>
    <Route
      {...rest}
      render={(props) =>
        isLoggedIn() ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  </Navigation>
);

问题

<Route path="*" component={Pages.NotFound} /> 匹配所有路由和渲染。可达后 Switch 无任何内容。

解决方案

  • Navigation 移动到 外部 的路由 Switch 中,其中包含一组应该用于渲染的路径。
  • 按照路径特异性的倒序排列路由。

示例:

<Router>
  <Route
    path={["/dashboard", "/my-playlist", "/new-released", "/search", "/profile"]}
    component={Navigation}
  />
  <Switch>
    <Route path="/redirect" component={Pages.Redirect} />
    <Route path="/login" component={Pages.Login} />
    <PrivateRoute path="/dashboard" component={Pages.Dashboard} />
    <PrivateRoute path="/my-playlist" component={Pages.MyPlaylist} />
    <PrivateRoute path="/new-released" component={Pages.NewReleased} />
    <PrivateRoute path="/search" component={Pages.CreatePlaylist} />
    <PrivateRoute path="/profile" component={Pages.Profile} />
    <Route exact path="/" component={Home} />
    <Route path="*" component={Pages.NotFound} />
  </Switch>
</Router>