我需要构建一个小型反应应用程序(我使用yarn和react-dom-router)才能真正实现“文件夹无关”。这意味着我不知道将部署该应用程序的 Web 服务器的文件夹。
可能是
/foo/
/bar/
/foo/bar/
/whatever/foo/bar/
所以我遵循了一些互联网智慧并添加到package.json
"homepage": "./"
我还在 vite.config.ts 中更改了这一点
base: "./"
但是现在我不知道如何设置路由器。我为初始路径尝试了几种不同的选项,但它们都不起作用:
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: "/", // I think the problem is there
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 />,
},
]);
export default router;
对于我尝试过的“主要”路径:
.
./
/
但它们都不起作用,我总是得到未找到的页面。有人解决过同样的问题吗
我的问题是我顽固地试图实现
createBrowserRouter
,这基本上与我的场景不兼容。
感谢@DrewReese 的评论,我切换到了
createHashRouter
import { createHashRouter } 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 = createHashRouter([
{
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 />,
},
]);
export default router;
有什么区别?基本上,
createHashRouter
在反应“内部”路由之前添加一个主题标签。通过这种方式,网络服务器会忽略该主题标签之后的任何内容,并始终解析为同一个文件,在本例中是我的index.html
。
对于资源,将路径更改为相关资源所需的就是
vite.config.js
中的这一行:
base: "./"