【问题标题】:Get the current route name into the component获取当前路由名称到组件中
【发布时间】:2016-05-09 12:52:38
【问题描述】:

我试图不使用 :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
 }
` 

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    根据您使用的 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>;
        }
    }
    

    【讨论】:

    • 谢谢,终于有最新的sn-p代码了!
    • 在几行代码中提供的基本相同的解决方案可能会有所帮助:stackoverflow.com/a/37523743
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多