同构反应-路由器-冗余同步历史中间件

Isomorphic react-router-redux syncHistory middleware

本文关键字:同步 历史 中间件 冗余 路由器 同构      更新时间:2023-09-26

来自 react-router-reduxsyncHistory接受从 react-router browserHistory的参数。在服务器上,调用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

正如您所观察到的browserHistory在服务器上不起作用,因为它使用浏览器中内置的历史记录 API。在服务器上,您必须将其替换为类似 history/lib/createMemoryHistory ,例如

import createHistory from 'history/lib/createMemoryHistory';
const reduxRouterMiddleware = syncHistory(createHistory);
...

有关历史记录的更多信息,请参阅 React 路由器文档。


从 React Router 2 开始,文档 createMemoryHistory 作为 React Router 的一部分包含在内。

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