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

Vite构建预览时React Router Dom嵌套路由报错问题

React项目构建后嵌套路由报错问题

问题现象

使用vite dev运行React项目一切正常,但执行vite build && vite preview后,应用抛出如下错误:

index-26685beb.js:4306 Error
    at invariant (App-1ae6b17c.js:34:11)
    at useRoutes (App-1ae6b17c.js:619:27)
    at Routes (App-1ae6b17c.js:847:10)
    at Xh (index-26685beb.js:3841:7)
    at Wk (index-26685beb.js:6937:11)

排查发现错误来自react-router-dom的useRoutes函数,触发点为useInRouterContext()返回false时的断言校验。

项目路由结构如下:

根App.jsx代码

const Project = () => {
  const loc = useParams();
  const { export: componentexport } = projectMap[loc.id];
  const Component = lazy(componentexport);
  return (
     <Suspense fallback={<Loading />}>
        <Component />
     </Suspense>
  )
}

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path={HOME.to} element={<Home />} />
        <Route path={PROJECTS.to} element={<Projects />} />
        <Route path={LOADING.to} element={<Loading />} />
        <Route path="/projects/:id/*" element={<Project />} />
      </Routes>
    </Router>
  );
}

嵌套项目组件代码

const Root = () => {
  return (
    <>
      <Navbar />
      <Outlet />
      <Footer />
    </>
  )
}

const App = () => {
  return (
    <Routes>
      <Route path='/' element={<Root />}>
        <Route path='' element={<Home />} />
        <Route path='about' element={<About />} />
      </Route>
    </Routes>
  )
}

移除<Project/>组件内的路由后,应用恢复正常。

核心结论

React Router完全支持嵌套路由,Vite构建本身也没有限制嵌套路由的使用,报错根源在于代码实现细节,无需额外配置Vite。

问题原因与解决方案

1. 上下文传递异常

构建优化(如代码分割、tree shaking)可能导致懒加载组件未能正确继承根<Router>的上下文,触发useInRouterContext()返回false。

解决方法:显式传递路由上下文给懒加载组件:

import { useContext } from 'react';
import { NavigationContext } from 'react-router-dom';

const Project = () => {
  const loc = useParams();
  const navigationContext = useContext(NavigationContext);
  const { export: componentexport } = projectMap[loc.id];
  const Component = lazy(componentexport);
  return (
     <Suspense fallback={<Loading />}>
       <NavigationContext.Provider value={navigationContext}>
         <Component />
       </NavigationContext.Provider>
     </Suspense>
  )
}

2. 嵌套路由路径配置错误

外层路由使用/projects/:id/*(通配符匹配子路径),但嵌套组件内使用绝对路径/,导致路径匹配逻辑冲突。

解决方法:改用相对路径配置嵌套路由,同时用index替代空path更规范:

// 嵌套项目组件的代码修改
const ProjectApp = () => {
  return (
    <Routes>
      <Route path='' element={<Root />}>
        <Route index element={<Home />} />
        <Route path='about' element={<About />} />
      </Route>
    </Routes>
  )
}

3. 组件名称冲突

嵌套组件内的App与根组件App重名,可能导致构建时代码混淆。

解决方法:将嵌套组件的App重命名为唯一名称(如ProjectApp)。

4. 版本兼容性问题

旧版本react-router-dom可能与Vite构建存在兼容性问题。

解决方法:升级至最新稳定版:

npm install react-router-dom@latest

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:45:11