部署在不同位置(子目录)的 React-router 应用程序 [英] React-router app deployed on different locations (subdirectories)
问题描述
我有一个 react-router 应用程序,我必须将其部署在不同的位置(子目录),因此基本名称会发生变化.例如它应该有以下路径:
I have a react-router app that I have to deploy on different locations (subdirectories), so the basename would change. For example it should have the following paths:
/
(生产)/appname/env1
/appname/env2
我想使用浏览器历史记录,所以我从 react-router 实现了 BrowserRouter
,但我无法向它传递静态基本名称.显然路由将不起作用,例如,如果我没有将任何基本名称传递给 BrowserRouter
,如果我的主页路由是:
I want to use Browser History, so I implemented the BrowserRouter
from react-router, but I cannot pass to it a static basename. And obviously the routing won't work, for example if I don't pass any basename to BrowserRouter
, if my homepage route is:
<Route path="/" 精确组件={MyComponent}/>
访问 /appname/env1
或 /appname/env2
时不起作用.
it won't work when accessing to /appname/env1
or /appname/env2
.
有没有办法用 react-router 实现我想要的?
Is there a way to achieve what I am looking for with react-router?
推荐答案
这对我有用:
<Router basename={window.location.pathname.replace(/(\/[^/]*)$/, "")}>
这没有文档中要求的尾部斜杠:https://reactrouter.com/web/api/BrowserRouter/basename-string
this has no trailing slash as required in docs: https://reactrouter.com/web/api/BrowserRouter/basename-string
示例
var pathname = "/pathname/routeName"
console.log(pathname.replace(/(\/[^/]*)$/, "") //returns "/pathname"
这篇关于部署在不同位置(子目录)的 React-router 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!