2016-02-01 50 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

相关问题