2017-05-04 72 views
3

我正在編寫React-on-Rails(v。5)應用程序,並且遇到問題。當我訪問路徑accounts/:account_id/letters/new時,React-Router正在安裝EmailShowComponent,當我想要它掛載EmailSendComponent時。react-router安裝了錯誤的組件

這是我的app.js文件:

<Router history={browserHistory}> 
    <Route path="/accounts/:id" component={AccountShowContainer} /> 
    <Route path="/accounts/:account_id/letters/:id" component={EmailShowComponent} /> 
    <Route path="/accounts/:account_id/letters/new" component={EmailSendComponent} /> 
</Router> 

這是我main.js文件:

import 'babel-polyfill'; 
import React from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App'; 

$(function(){ 
ReactDOM.render(
    <App />, 
    document.getElementById('app') 
) 
}); 

而且我放在裏面的每個生成相關的HTML頁面"<div id="app">"標籤路由器的這些路徑。

任何想法可能會造成這種情況?

+1

你的路由的順序;沒有什麼說'new'不是一個有效的ID。 –

回答

5

問題是路徑/accounts/:account_id/letters/new也滿足路徑/accounts/:account_id/letters/:id。區別在於id變爲"new"

爲了解決這個問題,只需簡單更換你的路由的順序:

<Router history={browserHistory}> 
    <Route path="/accounts/:id" component={AccountShowContainer} /> 
    <Route path="/accounts/:account_id/letters/new" component={EmailSendComponent} /> 
    <Route path="/accounts/:account_id/letters/:id" component={EmailShowComponent} /> 
</Router> 

欲瞭解更多信息,從官方文檔退房the Precedence section

最後,路由算法嘗試以 的順序匹配路線,從上到下定義它們。所以,當你有兩個兄弟路線 你應該確保第一個不匹配所有可能的path s,可以 匹配後面的兄弟姐妹。例如,做到這一點:

<Route path="/comments" ... /> 
<Redirect from="/comments" ... /> 
+1

謝謝,這工作得很好! – John