首页 > 解决方案 > 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 等。

或者也许我遗漏了一些东西并且它是可行的?

标签: reactjsreact-routercreate-react-app

解决方案


推荐阅读