我有一个如下的路由器:
<Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="login" component={Login}/> </Route> </Router>
这是我要实现的目标:
/login
/
所以现在我想以检查用户的状态App的componentDidMount,然后做一些事情,如:
App
componentDidMount
if (!user.isLoggedIn) { this.context.router.push('login') } else if(currentRoute == 'login') { this.context.router.push('/') }
这里的问题是我找不到获取当前路由的API。
我发现建议使用Router.ActiveState mixin和路由处理程序来解决此已关闭的问题,但是现在似乎已弃用了这两个解决方案。
阅读更多文档后,我找到了解决方案:
https://github.com/ReactTraining/react-router/blob/master/packages/react- router/docs/api/location.md
我只需要访问location组件实例的注入属性,例如:
location
var currentLocation = this.props.location.pathname