2016-02-01 90 views
0

我想不使用:if(window.location)來獲取我當前的路由。獲取當前路由名稱到組件

我正在處理一個代碼,其中已經定義了路由器,並且該組件已被寫入。我試圖從組件中訪問路由器信息,因爲我需要根據路由應用一個類名。

這裏的路由器的樣子:

export const createRoutes = (dispatch, getState) => ( <Route component={AppLayout} > <Route path="/" component={Home} onEnter={(nextState, replaceState) => { console.log('on Enter/= ', nextState); nextState.test = 'aaaa'; //can't seem to pass states here.... }} />

然後在我的組件:

render() { 
    //I want to access my super router or location . in fact 
    // I just want to know if currentURl === '/' 

    //and after reading the react-router doc 5 times - my head hurts 
    // but I still hope to get an answer here before putting a window.location 
} 
` 

回答

2

取決於哪個路由器的陣營版本您使用的是有機會獲得可用不同的對象在組件的context上。

MyComponent.contextTypes = { 
    location: React.PropTypes.object 
} 

這將使你做到以下幾點

render() { 
    if (this.context.location.pathname === '/') { 
     return <h1>Index</h1>; 
    } else { 
     return <h2>Not index</h2>; 
    } 
} 
+0

感謝您的! – Ant

+0

謝謝,最後一個代碼片斷是最新的! – Sephy

+0

基本上相同的解決方案提供了幾行代碼,可能會有所幫助:http://stackoverflow.com/a/37523743 – Slawoj

相關問題