如何在react-router 2.0.0-rc5中获取当前路由

JavaScript

伽罗飞云

2020-03-13

我有一个如下的路由器:

<Router history={hashHistory}>
    <Route path="/" component={App}>
        <IndexRoute component={Index}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>

这是我要实现的目标:

  1. 将用户重定向到(/login如果未登录)
  2. 如果用户/login已登录时尝试访问,请将其重定向到root/

所以现在我想以检查用户的状态AppcomponentDidMount,然后做一些事情,如:

if (!user.isLoggedIn) {
    this.context.router.push('login')
} else if(currentRoute == 'login') {
    this.context.router.push('/')
}

这里的问题是我找不到获取当前路由的API。

我发现建议使用Router.ActiveState mixin和路由处理程序来解决此已关闭的问题,但是现在似乎已弃用了这两个解决方案。

第1384篇《如何在react-router 2.0.0-rc5中获取当前路由》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
村村小小十三 2020.03.13

以同样的方式为我工作:

...
<MyComponent {...this.props}>
  <Route path="path1" name="pname1" component="FirstPath">
  ...
</MyComponent>
...

然后,我可以在MyComponent函数中访问“ this.props.location.pathname”。

我忘了那是我...)))以下链接介绍了更多有关制作导航栏的信息:react router this.props.location

GOMandy 2020.03.13

对于2017年有相同问题的所有用户,我可以通过以下方式解决:

NavBar.contextTypes = {
    router: React.PropTypes.object,
    location: React.PropTypes.object
}

并像这样使用它:

componentDidMount () {
    console.log(this.context.location.pathname);
}
宝儿Sam 2020.03.13

App.js添加以下代码并尝试

window.location.pathname
卡卡西Sam 2020.03.13

从3.0.0版开始,您可以通过调用以下命令获取当前路由:

this.context.router.location.pathname

示例代码如下:

var NavLink = React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },

    render() {   
        return (
            <Link {...this.props}></Link>
        );
    }
});
樱GO 2020.03.13

阅读更多文档后,我找到了解决方案:

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

我只需要访问location组件实例的注入属性,例如:

var currentLocation = this.props.location.pathname
西里阳光 2020.03.13

如果使用历史记录,则路由器会将所有内容从历史记录中放入该位置,例如:

this.props.location.pathname;
this.props.location.query;

得到它?

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android