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

新手上路,请多包涵

我有一个如下所示的路由器:

 <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 和路由处理程序,但看起来这两个解决方案现在已被弃用。

原文由 wxtry 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 506
2 个回答

您可以使用获取当前路线

const currentRoute = this.props.routes[this.props.routes.length - 1];

…这使您可以从最低级别的活动 <Route ...> 组件访问道具。

鉴于…

 <Route path="childpath" component={ChildComponent} />

currentRoute.path 返回 'childpath'currentRoute.component 返回 function _class() { ... }

原文由 colllin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题