【问题标题】:Can I set a base route in react-router我可以在 react-router 中设置基本路由吗
【发布时间】:2016-11-06 21:04:53
【问题描述】:

假设我的应用的基本网址是 example.com/app

是否可以在 react-router 中设置基本路由,而不是将所有路由都写成

/app/a
/app/b
/app/c

我可以将它们指定为

a
b
c

我尝试了在docs 中找到的以下示例,但它不起作用(页面不会显示任何内容)。也许是因为我使用的是 react-router@3.0.0-alpha.1,或者我做错了什么。

import { useRouterHistory } from 'react-router'
import { createHistory } from 'history'

const history = useRouterHistory(createHistory)({
  basename: '/app'
})

const Root = ({store}) => (
    <Provider store={store}>
        <Router history={history}>
            <Route path='/' component={App}>
                ...
            </Route>
        </Router>
    </Provider>
)

【问题讨论】:

  • 问题解决了吗?如果是,请发布答案。
  • @Learner 不。我放弃并开始输入完整的路线,实际上发现它更干净。
  • 真的吗?没有简单的解决方案吗?我已经搜索并尝试了一些想法,但没有任何运气(但我是新手)。

标签: react-router


【解决方案1】:

使用最新的react router (v4),您可以轻松做到这一点

<BrowserRouter basename="/calendar">
  <Link to="/today"/> // renders <a href="/calendar/today">
</BrowserRouter>

【讨论】:

  • 有没有办法用动态路径字段来做到这一点?像/calendar/:year/:month/:day/event 可能在哪里,例如/calendar/11/4/21/event
  • 为什么不把:year/:month/:day/event 部分放在Link to=中?
  • 重要的是在这里指出文档似乎是错误的正确使用 标签。文档中看到的自动关闭标签将无效。您需要将 标签包裹在所有 和其他路由标签周围。该示例应为: ...
  • 不幸的是,这似乎不再起作用了
  • @Madeo 你能提供一个新的答案吗?我会重定向
【解决方案2】:

如果你想使用&lt;Router /&gt;,它可以让你访问历史对象,允许你直接从js中通过history.push('/my-path')方法改变页面。您将面临 BrowserRouter 没有可用的history 属性,路由器没有可用的basename 的问题。

解决方法如下:

const App: React.FC = () => {
  // do not put a slash at the end of the basename value.
  const history = createBrowserHistory({ basename: '/your-base-name' });

  return <Router history={history}>
           ...
         </Router>;
}

所有位置的基本 URL。如果您的应用程序是从服务器上的子目录提供的,您需要将其设置为子目录。格式正确的基本名称应该有一个前导斜杠,但没有尾随斜杠

https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-30
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2017-04-08
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多