小编典典

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

reactjs

我有一个如下的路由器:

<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和路由处理程序来解决此已关闭的问题,但是现在似乎已弃用了这两个解决方案。


阅读 247

收藏
2020-07-22

共1个答案

小编典典

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

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

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

var currentLocation = this.props.location.pathname
2020-07-22