如何在 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
,请将其重定向到 root/
- 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.
我发现 this closed issue 建议使用 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屋!