children 路线上的 404 页面未按预期工作

404 page on Route not working as expected with children

我有一个包含两个 children 的用户路由。
我在 url 与用户不匹配的情况下使用了 path="*",因此它会 returns UserNotFoundPage.

问题是,虽然当 url 是 .../user/someIncorrectUsername 时它确实给我 UserNotFoundPage ,但如果我只输入 .../user/.../user 它会给我一个空白页面.虽然我希望它能让我进入 UserNotFoundPage。

我怎样才能得到这种行为?

这是我的代码:

<Router>
  <Routes>
    {/* PUBLIC */}
    <Route path="*" element={<Navigate replace to="/welcome"/>}/>
    <Route path="/welcome" element={<HomePage/>}/>
    <Route path="/dashboard" element={<DashboardPage/>}/>
    {/* RESTRICTED */}
    <Route path="/login" element={<LoginPage/>}/>
    {/* PRIVATE */}
    <Route path="/user" element={<Users/>}>
      <Route path="*" element={<UserNotFoundPage/>}/>
      <Route path="username" element={<UserProfilePage/>}>
    </Route>
    </Route>
  </Routes>
</Router>

function useAuth() {
  return true;
}

function HomePage() {
  return (
    <div>
      <h1>HOME PAGE</h1>
    </div>
  )
}

function UserNotFoundPage() {
  return (
    <div>
      <p>User not found</p>
    </div>
  )
}

function Users() {
  const auth = useAuth();
  return auth ? <Outlet/> : <Navigate to="/login"/>;
}

function UserProfilePage() {
  return (
    <div>
      <h4>USER PROFILE PAGE</h4>
    </div>
  )
}

function LoginPage() {
  return (
    <div>
      <h2>
        Login page
      </h2>
    </div>
  )
}

这里的问题是,抽象地“/user”也代表了一个路由路径,可以通过Outlet匹配和渲染,但是没有内容可以在上渲染 匹配“/用户”路径。

An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.

您可以将 UserNotFoundPage 路由指定为 匹配并呈现在“/user”上的路由与任何不匹配的“/user/*”路径一样,将其指定为索引路由。

<Route path="/user" element={<Users/>}>
  <Route index path="*" element={<UserNotFoundPage/>}/>
  <Route path="username" element={<UserProfilePage/>}>
</Route>