获取当前路由名称到组件中

Get the current route name into the component

我尽量不使用 :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
 }
` 

根据您使用的 React Router 版本,您可以访问组件 context 上可用的不同对象。

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

这将使您能够执行以下操作

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