【问题标题】:How to configure a basename in React Router 3.x如何在 React Router 3.x 中配置基本名称
【发布时间】:2017-06-30 03:07:22
【问题描述】:

我有一个应用程序在嵌套的 url 上运行,而不是在根目录下。比如说example.com/app

我读到 here 在 react router 2.x 中您可以配置基本名称。

如何在 react router 3.x 中做到这一点?

仅供参考,我也在使用react-router-redux 包。

【问题讨论】:

    标签: reactjs react-router browser-history react-router-redux


    【解决方案1】:

    我认为 React Router 文档中有关配置历史记录的部分是您正在寻找的内容:

    https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md#customize-your-history-further

    这是一个与 react-router-redux 集成的完整示例(排除了一些不必要的信息):

    import React from 'react';
    import ReactDOM from 'react-dom';
    import createBrowserHistory from 'history/lib/createBrowserHistory';
    import { useRouterHistory } from 'react-router';
    import { syncHistoryWithStore } from 'react-router-redux';
    
    import Root from './containers/Root';
    import configureStore from './store/configureStore';
    
    const historyConfig = { basename: '/some-basename' };
    const browserHistory = useRouterHistory(createBrowserHistory)(historyConfig);
    
    const store = configureStore({ initialState, browserHistory });
    const history = syncHistoryWithStore(browserHistory, store, {
      selectLocationState: (state) => state.router,
    });
    
    ReactDOM.render(
      <Root history={history} store={store} />,
      document.getElementById('root')
    );
    

    【讨论】:

    • 我认为这只适用于 react-router 2.x
    • React 路由器 3.x 本质上是没有弃用 API 的 2.x。我会试一试并发布任何错误
    • Uncaught Error: Expected the routing state to be available either as `state.routing` or as the custom expression you can specify as `selectLocationState` in the `syncHistoryWithStore()` options. Ensure you have added the `routerReducer` to your store's reducers via `combineReducers` or whatever method you use to isolate your reducers.
    • 检查上面的例子。 syncHistoryWithStore 的第三个参数是一个选项对象。 selectLocationState 传递了一个选择器,该选择器指向您的路由状态。如果您不想指定此项,请将您的路由器命名为在您的根 combineReducers 中声明“路由”作为错误状态。
    • 链接好像坏了。有人知道它现在住在哪里吗?
    【解决方案2】:

    React Router 中不再存在此功能。我遇到了类似的问题并找到了此修复程序。

    第 1 步: 安装历史记录 (3.0.0)

    npm install --save history@3.0.0

    第 2 步: 从路由器文件(带有&lt;Router&gt; 的文件)的历史记录中导入 { useBasename }:

    import { useBasename } from 'history'

    第 3 步:修改您的 &lt;Router&gt;,如下例所示:

    &lt;Router history={ useBasename(() =&gt; browserHistory)({ basename: '/app' }) }&gt;

    【讨论】:

    • 宾果游戏。完美运行。谢谢!
    猜你喜欢
    • 2023-04-03
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多