【问题标题】:browserHistory undefined with React Router 2.00 release candidates使用 React Router 2.00 候选版本未定义 browserHistory
【发布时间】:2016-01-16 00:02:36
【问题描述】:

使用 React Router 2.0.0rc1-5 我在导入后将 browserHistory 设为未定义:

import { browserHistory } from 'react-router'

该软件包似乎安装正确,但无论版本如何,无论是在服务器还是客户端,我都得到了相同的结果。

也许这是一个已知的错误?

【问题讨论】:

  • 使用较新版本的react-router,您可以从history 包中获得历史创建器。看看the docs
  • 从master分支来看,我相信他们现在实际上是在将browserHistory打包到react-router中
  • 使用 2.0 rcs,我在服务器上得到未定义...在浏览器中我得到 connect.js?243b:60 Uncaught TypeError: finalMapStateToProps is not a function(这似乎是 Redux 问题)。我认为这与 React Router 的渲染有关,因为除非我从 renderToString 中删除路由器,否则我会在服务器上收到相同的错误
  • 明白了。如果我是reading the code correctly,它实际上应该在服务器上返回undefined。您不会使用服务器上的历史记录,而是选择match and RoutingContext。并且浏览器错误听起来像是 Redux 配置问题,可能在您的代码中 - 随意在上面添加它,我们可以看看。
  • 看起来好像实际上是 Redux 语法问题。正如你所说,一旦我不在服务器上使用browserHistory,我就避免了未定义的问题。我的 redux 错误与我在容器中使用 connect() 有关。感谢您的帮助!

标签: reactjs react-router redux


【解决方案1】:

查看 useRouterHistory: https://github.com/rackt/react-router/blob/master/upgrade-guides/v2.0.0.md#using-custom-histories

我在服务器端使用这个:

import {Router, RouterContext, match, useRouterHistory} from 'react-router';
import {createMemoryHistory} from 'history';

// ...
const appHistory = useRouterHistory(createMemoryHistory)({});
const component = (
  <Provider store={store} key="provider">
    <Router routes={routes} history={appHistory} />
  </Provider>
);

【讨论】:

  • 你可以安装react-router 3.0 版,像这样:npm install --save react-router@3.0 也应该更新你的webpack配置文件。你很高兴。
【解决方案2】:

安装 react-router 3.0 版

npm install --save react-router@3.0

yarn add react-router@3.0

然后,这两种方法都有效:

方法一

import { Router, useRouterHistory } from 'react-router';
import {createMemoryHistory} from 'history';
import routes from './routes';

const appHistory = useRouterHistory(createMemoryHistory)({});

ReactDOM.render(
    <Router history={appHistory} routes={routes}/>,
    document.getElementById('root')
);

方法二

import { Router, browserHistory } from 'react-router';
import routes from './routes';

ReactDOM.render(
    // or hashHistory
    <Router history={browserHistory} routes={routes}/>,
    document.getElementById('root')
);

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 2020-03-21
    • 2017-03-24
    • 1970-01-01
    • 2019-06-17
    • 2017-09-13
    • 2016-06-01
    • 2016-04-28
    • 2023-03-30
    相关资源
    最近更新 更多