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

IT技术 javascript reactjs react-router
2021-04-19 18:38:57

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

<Router history={hashHistory}>
    <Route path="/" component={App}>
        <IndexRoute component={Index}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>

这是我想要实现的目标:

  1. /login如果未登录,则将用户重定向到
  2. 如果用户/login在已经登录的情况下尝试访问,请将其重定向到 root/

所以现在我正在尝试检查App's 中的用户状态componentDidMount,然后执行以下操作:

if (!user.isLoggedIn) {
    this.context.router.push('login')
} else if(currentRoute == 'login') {
    this.context.router.push('/')
}

这里的问题是我找不到获取当前路线的 API。

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

6个回答

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

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

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

var currentLocation = this.props.location.pathname
谢谢,链接很有帮助!
2021-05-24 18:38:57
您需要确保将此添加到您的组件中 static contextTypes = { router: React.PropTypes.object }
2021-05-25 18:38:57
如果它在你的子组件中不可用,你只需要使用 withRouter()
2021-06-08 18:38:57
它在某些子组件中不可用,但我设法通过 prop 传递它们。
2021-06-17 18:38:57
对我来说(v2.8.1),它可以通过this.state.location.pathname(而不是道具)获得。
2021-06-17 18:38:57

您可以使用获取当前路线

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

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

鉴于...

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

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

这是一个很好的方法,因为它保留了路由上定义的任何自定义属性。this.props.location失去这些自定义属性。
2021-05-24 18:38:57
并获得以前的路线(即后退按钮+标签),您可以使用 this.props.routes.length - 2
2021-06-18 18:38:57

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

this.props.location.pathname;
this.props.location.query;

得到它?

也许你可以扩展你的答案,有更多的投入和一些参考?现在太笼统了
2021-06-19 18:38:57

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

this.context.router.location.pathname

示例代码如下:

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

    render() {   
        return (
            <Link {...this.props}></Link>
        );
    }
});

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

NavBar.contextTypes = {
    router: React.PropTypes.object,
    location: React.PropTypes.object
}

并像这样使用它:

componentDidMount () {
    console.log(this.context.location.pathname);
}
由于PropTypes现在是一个独立的依赖,想到再补充: import PropTypes from 'prop-types'; ... NavBar.contextTypes = { router: PropTypes.object, location: PropTypes.object };
2021-06-05 18:38:57