reactjs - React 路由器 - 构建应用程序的动态基本名称
问题描述
情况
我正在创建一个在其中嵌入反应应用程序的后端库(例如 java 库或 go 模块等,没关系)。后端将公开提供build
文件夹内容的处理程序端点。该库的目标是成为用户应用程序的一部分,并且用户应该能够将其附加到他们想要的任何路径。它可以是简单的根目录/
,也可以是一些自定义路径,例如https://users-site.com/my-custom-path
假设这个库是“管理”面板,可以通过/admin
路径访问,或者/my-custom-path
在这种情况下。
问题
嵌入式库的位置可以是相对于主机的任何位置。
应用程序的小片段:
ReactDOM.render(
<React.StrictMode>
<BrowserRouter basename="/my-custom-path">
<Routes/>
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
export const Routes = () => {
const history = useHistory()
return (
<Router history={history}>
<Switch>
<Route exact path="/" component={Root}/>
<Route path="/first/:param?" component={First}/>
<Route path="/second/:param?" component={Second}/>
</Switch>
</Router>
)
}
export const Root = () => {
const history = useHistory()
return (
<div>This is root
<button onClick={() => history.push(`/first/some-param`)}>To First</button>
</div>
)
}
// First component is identiacal to Root component
<button onClick={() => history.push(`/second`)}>To Second</button>
// Second component
<button onClick={() => history.push(`/`)}>Back to root</button>
在"homepage": "/my-custom-path",
package.json
问题是,为了让 React Router 工作,我必须指定basename
哪个应该与用户决定在其上提供库的端点匹配,这是不可能的,因为必须在构建时指定 basename。
此外homepage
,属性必须准确(不能是相对的,例如"."
),因为当浏览器刷新发生时,它会加载相对于基本位置而不是当前路径的静态文件
解决方案
目前,我看到的唯一解决方案是将其硬编码basename
为某个唯一值,并强制库的所有用户在他们的应用程序的这个唯一路径上拥有这个 mini-ui。(硬编码根不是一个选项,因为用户可能有其他用户界面)
或者放弃 SPA 并做一些基本的服务器端渲染,例如 thymeleaf、go-templates 等。
或者也许我遗漏了一些东西并且它是可行的?
解决方案
推荐阅读
- c++ - boost::asio::co_spawn 在 MSVC 中未定义
- mysql - 如何使用按 XXX 分组,并正确使用聚合函数?具有最小值
- r - 根据百分等级创建虚拟变量
- android - 如何从软键盘 Android 获取 KeyCode
- c# - “Windows 桌面类库”模板能否用于创建多个 ASP.NET Web 应用程序使用的类库?
- angular - Firebase中子目录中的角度路由问题
- optimization - 如何区分负变量和正变量?
- c# - 如何从 linq 中的数据表中动态选择?
- c++ - 构建makefile的问题
- python - Python Split on \t 'fooled' by text with )