React-router导致无法读取未定义的属性'listen'

时间:2016-08-19 14:15:27

标签: javascript reactjs react-router isomorphic-javascript

在服务器端使用react-router构建webpack时,我遇到了奇怪的js异常:

Cannot read property 'listen' of undefined

我该如何解决?

1 个答案:

答案 0 :(得分:0)

browserHistory是由createRouterHistory生成的代码,如果未定义DOM,则返回undefined。这就是你犯这个错误的原因。

解决方案是导入useRouterHistory并以createMemoryHistory以某种方式替换它,其目的是用于服务器端渲染。 webpack的实现:

# application.js
import { Router, useRouterHistory } from "react-router"
import { createHistory } from "history"

const browserHistory = useRouterHistory(createHistory)({ queryKey: false })

<Router history={history}>
  ...bla-bla
</Router>

# webpack.config.server.js - sends this code to react server
new webpack.NormalModuleReplacementPlugin(
  /createBrowserHistory/,
  require.resolve("./node_modules/react-router/lib/createMemoryHistory.js")
)