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)
这就是我想要实现的目标:
/login如果未登录,则将用户重定向到/login在登录时尝试访问,请将其重定向到root/所以现在我想以检查用户的状态App的componentDidMount,然后做一些事情,如:
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)
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)
得到它?
从版本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)
| 归档时间: |
|
| 查看次数: |
109796 次 |
| 最近记录: |