我有一个如下所示的路由器:
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="login" component={Login}/>
</Route>
</Router>
以下是我想要实现的目标:
/login
如果未登录/login
,请将其重定向到根用户因此,现在我尝试在App
的componentDidMount
中检查用户的状态,然后执行如下操作:
if (!user.isLoggedIn) {
this.context.router.push('login')
} else if(currentRoute == 'login') {
this.context.router.push('/')
}
这里的问题是我找不到获取当前路由的API。
我发现this closed issue建议使用Router.ActiveState混合和路由处理程序,但看起来这两种解决方案现在已被弃用。
发布于 2016-01-28 12:58:55
在阅读了更多的文档后,我找到了解决方案:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md
我只需要访问组件实例的注入属性location
,如下所示:
var currentLocation = this.props.location.pathname
发布于 2016-09-27 02:52:47
您可以使用以下命令获取当前路径
const currentRoute = this.props.routes[this.props.routes.length - 1];
通过...which,您可以从最低级别的active <Route ...>
组件访问属性。
鉴于..。
<Route path="childpath" component={ChildComponent} />
currentRoute.path
返回'childpath'
,currentRoute.component
返回function _class() { ... }
。
发布于 2016-05-23 01:07:48
如果您使用历史记录,则路由器会将历史记录中的所有内容放入该位置,例如:
this.props.location.pathname;
this.props.location.query;
明白了吗?
https://stackoverflow.com/questions/35031911
复制相似问题