React-Router - Uncaught TypeError: Cannot read property 'getCurrentLocation' of undefined

React-Router - Uncaught TypeError: Cannot read property 'getCurrentLocation' of undefined

我使用的是最新版本的 react-router(版本 ^3.0.0)。

我使用 ES5 编写了以下路由:

routes.js:

var React = require("react");
var Router = require("react-router");
var AuthorPage = require('./components/authors/authorPage')
var App = require('./components/app')
var Route = Router.Route;

var routes = (
    <Route path="/" component={App}>
        <Route path="authors" component={AuthorPage}/>
     </Route>
);

module.exports = routes;

在另一个名为 main.js 的 JS 文件中,我执行以下调用:

main.js:

var React= require("react");
var ReactDom = require("react-dom");
var Router = require('react-router').Router;
var routes = require('./routes');
ReactDom.render(<Router routes={routes}></Router>, document.getElementById('app'));

当我 运行 代码时,我在 Google Chrome 开发人员工具中得到以下异常:

Uncaught TypeError: Cannot read property 'getCurrentLocation' of undefined

这是为什么?我错过了什么?

您没有将历史记录传递给您的 <Router>

查看 histories documentation 了解更多信息。

遇到同样的错误,这样解决了:

添加

var hashHistory = ReactRouter.hashHistory;

并且在 Router 中设置 history 等于 hashHistory

<Router history={hashHistory}>

所以在你的情况下:

var routes = (
<Router history={hashHistory}>
    <Route path="/" component={App}>
        <Route path="authors" component={AuthorPage}/>
     </Route>
</Router>
);