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

wxt*_*try 82 javascript reactjs react-router

我有一个如下的路由器:

<Router history={hashHistory}>
    <Route path="/" component={App}>
        <IndexRoute component={Index}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>
Run Code Online (Sandbox Code Playgroud)

这就是我想要实现的目标:

  1. /login如果未登录,则将用户重定向到
  2. 如果用户/login在登录时尝试访问,请将其重定向到root/

所以现在我想以检查用户的状态AppcomponentDidMount,然后做一些事情,如:

if (!user.isLoggedIn) {
    this.context.router.push('login')
} else if(currentRoute == 'login') {
    this.context.router.push('/')
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是我找不到API来获取当前路由.

我发现使用Router.ActiveState mixin和路由处理程序建议这个封闭的问题,但看起来这两个解决方案现在已被弃用.

wxt*_*try 111

在阅读了更多文档后,我找到了解决方案:

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

我只需要访问location组件实例的inject属性,如:

var currentLocation = this.props.location.pathname
Run Code Online (Sandbox Code Playgroud)

  • 它在一些子组件中不可用,但我设法通过prop传递它们. (5认同)
  • 你需要确保将它添加到你的组件`static contextTypes = {router:React.PropTypes.object}` (2认同)

col*_*lin 27

您可以使用当前路线

const currentRoute = this.props.routes[this.props.routes.length - 1];
Run Code Online (Sandbox Code Playgroud)

...允许您从最低级别的活动<Route ...>组件访问道具.

鉴于...

<Route path="childpath" component={ChildComponent} />
Run Code Online (Sandbox Code Playgroud)

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


小智 10

如果您使用历史记录,那么路由器会将所有内容放入历史记录中的位置,例如:

this.props.location.pathname;
this.props.location.query;
Run Code Online (Sandbox Code Playgroud)

得到它?

  • 也许你可以扩展你的答案,有更多的输入和一些参考?现在它太笼统了 (13认同)

Sit*_*thu 8

从版本3.0.0开始,您可以通过调用以获取当前路由:

this.context.router.location.pathname

示例代码如下:

var NavLink = React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },

    render() {   
        return (
            <Link {...this.props}></Link>
        );
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 7

对于2017年遇到相同问题的任何用户,我通过以下方式解决了这个问题:

NavBar.contextTypes = {
    router: React.PropTypes.object,
    location: React.PropTypes.object
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

componentDidMount () {
    console.log(this.context.location.pathname);
}
Run Code Online (Sandbox Code Playgroud)