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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 17:22:08