首页 > 解决方案 > react中如何在url开头放置参数

问题描述

我正在尝试构建一个简单的 POS 系统,不同企业中的不同用户可以访问该系统我想要实现的是,该网站托管在所有企业的一个地方,但他们通过具有唯一企业 ID 的 URL 访问它。

所以就像github通过加载用户配置文件

 https://github.com/USERNAME

我希望我的系统可以作为

 https://example.com/BUSINESS_ID

其他网址将紧随其后,即

https://example.com/BUSINESS_ID/menu
https://example.com/BUSINESS_ID/pos
https://example.com/BUSINESS_ID/supplies

我怎样才能通过反应来实现这一点。

我试过使用

`/:business_id/menu` 

等等在我的网址中,但页面只是加载空白任何关于通过反应实现这一目标的最佳方法的想法和建议将不胜感激

这就是我的路由方式

在 index.js 中

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path="/:business_id/" component={App} />
        <Route path="/" component={dashboard} exact />
      </Switch>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

在 app.js 中

  <Route path="/:business_id/"
    render={({ match: { url } }) => (
         <>
           <Route path={`${url}`} component={menu} exact />
             <Route path={`${url}orders`} component={orders} />
             <Route path={`${url}menu`} component={menu} />
         </>
     )}
  />

在我引入参数business_id之前一切正常

标签: reactjsreact-redux

解决方案


在您的 App.js 中尝试使用react-router match.path而不是match.url道具。

来自 React 文档:

  • path- (字符串)用于匹配的路径模式。用于构建嵌套的 <Route >s
  • url- (string) URL 的匹配部分。用于构建嵌套的 < Link >s

考虑路线/:businessIdmatch.path将是/:businessIdwhilematch.url:businessId填充值,例如/3423ui67x.


推荐阅读