2017-04-23 84 views
0

背景理解的變化作出反應,路由器V4

我有一門課程按照順序來學習React.js。這是一個偉大的,非常有幫助的,但我一直在工作中遇到錯誤react-router

從我讀過的時候,我正在嘗試學習,並同時理解它,所以會讓它更加混亂。

錯誤

warning.js:36警告:無法丙類型:該道具history被標記 如Router必需的,但它的值是undefined。 在路由器(在index.js:12)

問題

請能夠解釋爲什麼這不會在V4工作

<Router history={browserHistory}> 

"dependencies": { 
    "react": "^15.5.4", 
    "react-dom": "^15.5.4", 
    "react-router": "^4.1.1" 
    }, 

ReactDOM.render(
    <Router history={browserHistory}> 
     <Route path="/" component={Home} /> 
     <Route path="/services" component={Services} /> 
     <Route path="/portfolio" component={Portfolio} /> 
     <Route path="/about" component={About} /> 
     <Route path="/contact" component={Contact} /> 
     <Route path="*" component={Fourofour} /> 
    </Router> 

, 
    document.getElementById('root') 
); 
一些輕

進口

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { Router, Route, browserHistory } from 'react-router' 
import Fourofour from './containers/fourofour/Fourofour'; 
import Home from './containers/home/Home'; 
import Services from './containers/services/Services'; 
import Portfolio from './containers/portfolio/Portfolio'; 
import About from './containers/about/About'; 
import Contact from './containers/contact/Contact'; 
+0

你的意思是「這不適用於V4」?它會工作。代碼將被編譯。 –

+0

嘿,謝謝你的幫助。我要解決我的錯誤。如果你有時間你會介意看我目前的項目嗎? https://github.com/wuno/react-components – wuno

+0

你看到什麼錯誤? –

回答

1

變化

<Route path="/" component={Home} /> 

<Route exact path="/" component={Home} /> 

,你可能會得到更好的結果。正如您現在所知,/services(和其他路徑)也將匹配/路徑。

有關exact關鍵字的更多信息可在React Router V4 docs找到。

如果要指定在<Router> componenent歷史,你需要在你的代碼手動創建歷史(<BrowswerRouter>爲您創建它,所以你不需要指定history道具吧)。您可以通過創建一個新的文件,這樣做:

// utils/history.js 
import { createBrowserHistory } from 'history'; 

export default createBrowserHistory({ 
    /* pass a configuration object here if needed */ 
}); 

然後你需要的地方使用歷史:

import history from './utils/history'; 

<Router history={history}> 
... 

您還需要安裝史上包:

npm install history --save 

React Router V4文檔也有一個example of using a custom history

最後,如果您從未使用歷史記錄對象,則可以使用<BrowserHistory> component,它將爲您管理歷史記錄,而無需創建自定義歷史記錄對象。

+0

我改變了這一點,但我得到了同樣的問題。 warning.js:36警告:失敗的道具類型:道具'history'在'Router'中被標記爲必需,但其值爲'undefined'。 在路由器(在index.js:12) – wuno

+0

看到我更新的答案。 –

+0

是的,謝謝你我想弄清楚如何將它融入到我的項目中。但是我面臨的問題是理解爲什麼我當前的代碼不起作用。 – wuno