You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom如何为/private私有子路由配置专属404页面

问题根因

  1. 外层路由的<Switch>匹配到/private前缀的路由后,就会直接渲染<ProtectedRoutes>组件,不会继续向下走到全局的<NotFound>路由。而你当前的<ProtectedRoutes>内部的<Switch>只定义了两个合法子路由,没有加兜底匹配规则,访问/private下不存在的路径时,内部没有匹配结果就会返回空内容。
  2. 你把<Suspense>放在了<Switch>的直接子节点位置,<Switch>仅会识别<Route>、<Redirect>这类路由组件作为匹配项,非路由组件放在<Switch>直接子级会干扰匹配逻辑。

解决方案

调整<ProtectedRoutes>的结构,把<Suspense>移到<Switch>外层,同时在私有路由列表后添加兜底的404路由即可,修正后的代码如下:

const ProtectedRoutes = () => (
  <Suspense fallback={<Loader type="circle" />}>
    <Switch>
      {routes.map(({ component: Component, path, exact }) => (
        <Route path={`/private/${path}`} key={path} exact={exact ?? true}>
          <Component />
        </Route>
      ))}
      {/* 私有路由域下的兜底404路由 */}
      <Route>
        <NotFound />
      </Route>
    </Switch>
  </Suspense>
);

const routes = [
  {
    path: 'test',
    component: lazy(() => import('../components/private/logged/index')),
  },
  {
    path: 'otherTest',
    component: lazy(() => import('../components/private/logged/index')),
  }
];

补充说明

如果需要让/private根路径也展示指定内容(比如私有域首页或者404),可以在路由列表中新增一个path="/private"、exact={true}的路由规则,绑定对应的组件即可。

内容的提问来源于stack exchange,提问作者tetar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:24:02