我正在使用 React 和 React Router 构建一个非常简单的网页。我已经使用 NPM 安装了最新版本的 React Router 模块 (v3.0.0),在我的 index.js 文件中写了 3 个非常简单的路由:
import React, {Component} from 'react';
import {render} from 'react-dom';
import {Router, Route} from 'react-router';
//Import custom components
import About from '../components/about.js';
import Contact from '../components/contact.js';
import Sidebar from '../components/sidebar.js';
import Imagelist from '../components/image-list.js';
render(
<Router>
<Route component={Sidebar}>
<Route path="/" component={Imagelist}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
</Route>
</Router>,
document.getElementById('content')
);
但是当我尝试在本地打开页面时,我不断在控制台中收到此错误:
Uncaught TypeError: Cannot read property 'getCurrentLocation' of undefined(…)
当我检查错误时,这一行在 Router.js 中突出显示:
You have provided a history object created with history v2.x or earlier. This version of React Router is only compatible with v3 history objects. Please upgrade to history v3.x.
我已经尝试使用 NPM 安装这个历史模块的 v3,但我仍然收到这个错误。我什至不确定这是否是错误要求我做的。谁能告诉我我做的是否正确?
最佳答案
这可能是 react-router 3.0 的一个错误,因为我没有在文档中找到任何地方说它需要传递 history
。但是您只需要将其中一个历史记录选项传递给 Router
。我什至在 docs 中看到了一个没有传递历史的例子。 , 这可能已经过时了。
基本上您需要做的就是:
import {Router, Route, browserHistory} from 'react-router';
...
return (
<Router history={browserHistory}>
<Route component={Sidebar}>
<Route path="/" component={Imagelist}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
</Route>
</Router>
);
...
在此处查看更多详细信息 https://github.com/ReactTraining/react-router/blob/master/docs/guides/Histories.md
关于javascript - React-Router 的历史对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40455999/