React-Router的历史对象问题

History object issue with React-Router

本文关键字:问题 对象 历史 React-Router      更新时间:2023-09-26

我正在使用React和React路由器构建一个非常简单的网页。我使用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中突出显示:

您已经提供了一个使用history v2创建的历史对象。X或更早。这个版本的React Router只兼容v3版本的历史对象。请升级到历史记录版本3.x。

我已经尝试使用NPM安装这个历史模块的v3,但我仍然得到这个错误。我甚至不确定这是否是错误要求我做的。谁能告诉我我做的对不对?

这可能是react-router 3.0的一个bug,因为我没有找到任何地方说它需要在文档中传递history。但是您只需要将其中一个历史选项传递给Router。我甚至见过一个没有在文档中传递历史记录的例子,这可能已经过时了。

基本上你需要做的就是:

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