[英]How to get current route in react-router 2.0.0-rc5
我有一个如下所示的路由器:
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="login" component={Login}/>
</Route>
</Router>
这是我想要实现的目标:
/login
/login
时尝试访问/login
,请将其重定向到 root /
所以现在我试图在App
的componentDidMount
检查用户的状态,然后执行以下操作:
if (!user.isLoggedIn) {
this.context.router.push('login')
} else if(currentRoute == 'login') {
this.context.router.push('/')
}
这里的问题是我找不到获取当前路线的 API。
我发现这个关闭的问题建议使用 Router.ActiveState 混合和路由处理程序,但看起来这两个解决方案现在已被弃用。
阅读更多文档后,我找到了解决方案:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md
我只需要访问组件实例的注入属性location
,例如:
var currentLocation = this.props.location.pathname
您可以使用获取当前路线
const currentRoute = this.props.routes[this.props.routes.length - 1];
...这使您可以从最低级别的活动<Route ...>
组件访问道具。
鉴于...
<Route path="childpath" component={ChildComponent} />
currentRoute.path
返回'childpath'
并且currentRoute.component
返回function _class() { ... }
。
如果使用历史记录,则路由器将所有内容放入历史记录中的位置,例如:
this.props.location.pathname;
this.props.location.query;
得到它?
从 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);
}
在App.js
添加以下代码并尝试
window.location.pathname
您可以像这样使用“isActive”道具:
const { router } = this.context;
if (router.isActive('/login')) {
router.push('/');
}
isActive 将返回真或假。
使用 react-router 2.7 测试
以同样的方式为我工作:
...
<MyComponent {...this.props}>
<Route path="path1" name="pname1" component="FirstPath">
...
</MyComponent>
...
然后,我可以在 MyComponent 函数中访问“this.props.location.pathname”。
我忘记了我是...))) 以下链接描述了制作导航栏等的更多信息: react router this.props.location
尝试使用以下方法获取路径: document.location.pathname
在 Javascript 中,您可以分部分获取当前 URL。 查看: https : //css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.