如何在react-router 2.0.0-rc5中获取当前路由 [英] How to get current route in react-router 2.0.0-rc5
问题描述
我有一个类似如下的路由器:
I have a router like below:
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="login" component={Login}/>
</Route>
</Router>
这就是我要实现的目标:
Here's what I want to achieve :
- 如果未登录,将用户重定向到
/login
- 如果用户已登录时尝试访问
/login
,请将其重定向到根/
- Redirect user to
/login
if not logged in - If user tried to access
/login
when they are already logged in, redirect them to root/
所以现在我正尝试在 App
的 componentDidMount
中检查用户的状态,然后执行以下操作:
so now I'm trying to check user's state in App
's componentDidMount
, then do something like:
if (!user.isLoggedIn) {
this.context.router.push('login')
} else if(currentRoute == 'login') {
this.context.router.push('/')
}
这里的问题是我找不到获取当前路线的API.
The problem here is I can't find the API to get current route.
我发现此已解决的问题建议使用Router.ActiveState mixin和路由处理程序,但看起来这两个解决方案现已弃用.
I found this closed issue suggested using Router.ActiveState mixin and route handlers, but it looks like these two solutions are now deprecated.
推荐答案
阅读更多文档后,我找到了解决方法:
After reading some more document, I found the solution:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md
我只需要访问组件实例的注入的属性 location
,例如:
I just need to access the injected property location
of the instance of the component like:
var currentLocation = this.props.location.pathname
这篇关于如何在react-router 2.0.0-rc5中获取当前路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!