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

React Router集成Suspense懒加载后NotFound页面始终显示问题

问题分析

你的404页面始终显示的核心原因是Switch的直接子元素不是Route组件:你把所有Route都包裹在了Suspense里面,而Switch只会识别直接子级的Route/Redirect,导致Suspense被直接渲染,内部的所有Route都会同时生效(失去了Switch的排他匹配特性)。同时,404路由错误地添加了exact属性,导致匹配逻辑异常。

解决方案

1. 调整AdminLayout的Switch与Suspense结构

将Suspense移到Switch外部,让Route成为Switch的直接子元素,这样Switch才能正常按顺序匹配路由:

return (
  <Fragment>
    <div className="adminContainer">
      <Suspense fallback={<div></div>}>
        <Switch>
          {routes.map((route, i) => {
            if (route.layout === '/admin') {
              return (
                <Route
                  path={route.layout + route.path}
                  component={route.component}
                  key={i}
                  // 仅给非404路由添加exact属性
                  exact={route.name !== 'notfound'}
                />
              );
            }
          })}
        </Switch>
      </Suspense>
    </div>
  </Fragment>
)

2. 确保404路由在routes数组的最后

Switch按数组顺序匹配路由,必须把404路由放在所有admin路由的最后,这样只有前面的路由都不匹配时,才会触发404:

const routes: Route[] = [
  {
    path: '/home',
    name: 'admin',
    icon: 'icon-signal',
    component: MyHomePage,
    layout: '/admin',
    text: 'Wellness',
  },
  {
    path: '/profile',
    name: 'admin',
    icon: 'icon-profile',
    component: ProfilePage,
    layout: '/admin',
    text: 'Profile',
  },
  {
    path: '/support',
    name: 'support',
    icon: 'default',
    component: LandingPage,
    layout: '/',
    text: 'Support',
  },
  // 404路由必须放在最后
  {
    path: '*',
    name: 'notfound',
    icon: '',
    component: NotFoundUrl,
    layout: '/admin',
    text: 'Notfound',
  },
]

3. 保持App.tsx的路由配置不变

App里的/admin路由不需要加exact,这样才能匹配所有/admin开头的子路径:

const App = () => {
  return (
    <Switch>
      <Route path="/admin" render={(props) => <AdminLayout />} />
      <Route path="/auth" render={(props) => <AuthLayout />} />
      <Route path="/soporte" render={(props) => <LandingPage />} />
      <Route path="/pago-movil" render={(props) => <GoToApp />} />
      <Redirect from="/" to="/auth/login" />
    </Switch>
  );
};
验证逻辑
  • 访问/admin/home或/admin/profile:Switch匹配对应路由组件,不会触发404
  • 访问/admin/xxx(未定义路由):前面路由均不匹配,最后触发404组件
  • 访问/auth或其他非admin路由:直接进入对应布局,不会加载AdminLayout内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:00:58