我正在从 React Router v5 升级到 v6。当我运行应用程序时,url 中没有基本名称,也没有加载任何内容,当我将/config2 添加到 url 时,一切都会显示出来。我在使用 v5 BrowserRouter basename Prop 时遇到错误。我正在尝试使用 React router v6 解决此问题,但尚未找到解决方案。它在 v5 上运行良好。有什么解决办法吗?
Root.tsx
<BrowserRouter basename="/config2">
<IntlProvider
messages={
LanguageOptions.find((option) => {
return option.locale === appState.locale;
})?.fileName
}
locale={appState.locale}
defaultLocale="en"
>
<ThemeProvider>{children}</ThemeProvider>
</IntlProvider>
</BrowserRouter>
这是我使用浏览器路由器的地方。
App.tsx
<>
<GlobalAlert />
{/* TODO: remove this once no longer necessary, after disconnecting legacy DCUI */}
{isAuthenticated && !legacyView && (
<div className={classes.app}>
{loadingCountryOptions ? (
<div className={classes.progressBar}>
<CircularProgress size="30px" />
</div>
) : (
<>
<Header />
<div className={classes.appContent}>
<Routes>
<Route path="/" element={<ProtectedRoutes />}>
<Route path="/configuration/configure" element={<Configuration />} />
<Route path="/configuration" element={<SummaryPage />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/appointments" element={<Appointments />} />
<Route path="/" element={<Navigate replace to="/configuration" />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</div>
<Footer />
</>
这是我列出所有其他页面路由的地方。
最佳答案
basename
属性应该与您的应用程序部署/运行的位置相匹配。在本例中,它从 "/config2"
子目录运行。您当前正在访问 "localhost:3000/"
而不是 "localhost:3000/config2"
。
本地开发服务器不知道从"./config2"
目录开始。
当应用程序尝试将绝对路径与路由器的 basename
进行匹配时,会发生错误,这是一个不同的目录。从 "/config2"
目录运行应用程序时,我无法重现任何错误,就像应用程序所期望的那样。
在本地手动导航到 "/config2"
。您可能还想添加一个 "homepage": "./config2"
或 "homepage": "."
条目到您的 package.json 中,以便路由可以相对于部署目录。
参见 Building for Relative Paths了解更多详情。
关于reactjs - 升级到 v6 时 BrowserRouter basename 属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71414067/