2016-11-07 83 views
6

我正在使用React和React路由器構建一個非常簡單的網頁。我已經安裝了最新版本的使用做出反應NPM路由器模塊(V3.0.0)的,書面3條非常簡單的路線在我的index.js文件:React-Router的歷史對象問題

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,但我仍然G解決這個錯誤。我甚至不確定這是錯誤要求我做的事情。任何人都可以告訴我,如果我做對了嗎?

+0

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> ); ... 

檢查更多的細節也許你還應該添加一些代碼到你的問題。 – Kevin

回答

12

這可能是來自react-router 3.0的一個bug,因爲我沒有找到任何地方說它需要通過文檔上的history。但您只需將其中一個歷史選項傳遞給Router即可。我甚至看到一個沒有通過docs歷史的例子,可能已經過時了。

基本上所有你需要做的是:這裏https://github.com/ReactTraining/react-router/blob/master/docs/guides/Histories.md

+0

太棒了,謝謝!這解決了它。你知道爲什麼這個'browserHistory'需要導入嗎? –

+0

@MaxineEllah,你可以在文檔中看到https://github.com/ReactTraining/react-router/blob/master/docs/guides/Histories.md有多種類型的歷史對象('browserHistory','hashHistory' ...),我以爲有一個默認的,所以你不需要通過任何,如果你不需要定製它。但它似乎要求你通過一個,我在他們的回購問題中提出。你可以在這裏關注https://github.com/ReactTraining/react-router/issues/4097 –

+0

謝謝,這真的很有幫助。 –