Isomorphic react-router-redux syncHistory中间件

时间:2016-02-02 17:53:35

标签: javascript reactjs react-router redux

来自syncHistory

react-router-redux会从browserHistory获取react-router的参数。在服务器上,调用syncHistory(browserHistory)并不真正起作用。我正在尝试使用中间件创建一个商店:

const { syncHistory } from 'react-router-redux'
const { browserHistory } from 'react-router'
const { createStore, applyMiddleware } from 'redux'

const reduxRouterMiddleware = syncHistory(browserHistory)
const createStoreWithMiddleware = applyMiddleware(
  routerReduxMiddleware
)(createStore)

在服务器上,我收到以下错误:

    unsubscribeHistory = history.listen(function (location) {
                                ^

TypeError: Cannot read property 'listen' of undefined

1 个答案:

答案 0 :(得分:1)

正如您所看到的,browserHistory无法在服务器上运行,因为它使用浏览器内置的历史记录API。在服务器上,您必须将其替换为history/lib/createMemoryHistory之类的内容,例如

import createHistory from 'history/lib/createMemoryHistory';

const reduxRouterMiddleware = syncHistory(createHistory);
...

有关历史记录的详细信息,请参阅React Router documentation

从React Router 2开始, docs,  createMemoryHistory包含在React Router的一部分中。

import createHistory from 'react-router/lib/createMemoryHistory';