使用Yarn与React-Router-Dom构建文件夹无关React应用的路由配置求助
解决方法
问题核心是createBrowserRouter缺少与Vite部署路径对应的basename配置,直接修改路由代码即可:
修改路由配置
import { createBrowserRouter } from "react-router-dom"; import { HomeView } from "./views/home"; import { SceneryView } from "./views/scenery"; import { NotFoundView } from "./views/not-found"; import { DefaultLayout } from "./layouts/default-layout"; import { PatientView } from "./views/patient"; import { PatientEndView } from "./views/patient-end"; import { CompletedView } from "./views/completed"; const router = createBrowserRouter( [ { path: "/", element: <DefaultLayout />, children: [ { index: true, element: <HomeView /> }, { path: "decision-pathways/scenery/:id", element: <SceneryView /> }, { path: "decision-pathways/patient/:sceneryId/:patientId", element: <PatientView /> }, { path: "decision-pathways/patient/end/:sceneryId/:patientId", element: <PatientEndView /> }, { path: "decision-pathways/completed", element: <CompletedView /> }, ], }, { path: "*", element: <NotFoundView /> }, ], { // 关键配置:绑定Vite的基础路径环境变量 basename: import.meta.env.BASE_URL, } ); export default router;
原理说明
- 你已经在
vite.config.ts中设置了base: "./",Vite会自动将应用实际部署的子路径注入到import.meta.env.BASE_URL中(比如部署在/foo/bar/时,该变量值为"/foo/bar/") createBrowserRouter的basename参数会让所有路由规则自动带上这个前缀,适配任意部署路径
服务器配置补充
因为使用浏览器路由(BrowserRouter),服务器需要将所有请求转发到index.html,否则刷新页面会出现404:
- Nginx配置示例:
location / { try_files $uri $uri/ /index.html; } - Apache配置示例(需启用
mod_rewrite):RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.html [L]
这样调整后,你的应用就能在任意子文件夹下正常运行,不会再跳转到NotFound页面。
内容的提问来源于stack exchange,提问作者Lorenzo
相关产品推荐
相关产品推荐

