在使用路由的时候,有的时候我们的界面只能够在登录之后才可以看的到,这个时候就需要使用路由权限控制了

找了资料发现一个就是我使用的方法,一个是高阶组件。 原谅菜鸟看不太懂不会使用高阶组件…………

首先在路由中做一个私有权限的限制,限制里面的path就是你的私有界面

router.js

 <Switch>
<Route path="/" exact component={Home} />
<PrivateRoute path="/MyOptional" component={MyOptional} />
<Route render={() => <Redirect to="/" />} />
</Switch>

想要跳转到path的里面,首先在PrivateRoute里面做登录判断条件

private.js

import React from 'react';
import {Route,Redirect,withRouter} from 'react-router-dom';
import PropTypes from 'prop-types';
//私有路由,只有登录的用户才能访问
class PrivateRoute extends React.Component{
componentWillMount(){
let isAuthenticated = sessionStorage.getItem("userName") ? true :false;
this.setState({isAuthenticated:isAuthenticated})
if(!isAuthenticated){
const {history} = this.props;
setTimeout(() => {
history.replace("/");
}, 1000)
}
}
render(){
let { component: Component,path="/",exact=false,strict=false} = this.props;
return this.state.isAuthenticated ? (
<Route path={path} exact={exact} strict={strict} render={(props)=>( <Component {...props} /> )} />
) : <Redirect
to={{
pathname: "/",
}} //这里必须使用redireact不能和上面一样使用<Route/> 因为会出现页面先跳转到myOption然后再跳转到首页的状况,这样用户体验不好
/> ;
}
}
PrivateRoute.propTypes ={
path:PropTypes.string.isRequired,
exact:PropTypes.bool,
strict:PropTypes.bool,
component:PropTypes.func.isRequired
}
export default withRouter(PrivateRoute);

这样就ok了

注:因为我的登录界面是在首页或者各个界面的模态框,所以这里我的路径直接都是如果没有登录,直接跳转首页的。如果大家的登录界面是单独的,那可以直接跳转到登录界面了

还有个tips就是,如果你的界面没有在路由中进行声明,然后又想要在界面中使用route相关的路径参数,就可以引入withRouter,在this.props中得到了

最新文章

  1. Jade之Interpolation
  2. hdoj 1875 畅通工程再续
  3. libmysqlclient.so.15: cannot open shared object file: No such file or directory
  4. ThinPHP第二十七天(kindEditor使用,$.each)
  5. ASP.NET——两个下拉框来实现动态联动
  6. openstack controller ha测试环境搭建记录(二)——配置corosync和pacemaker
  7. MinGW(GCC)编译DLL文件
  8. AngularJs parent index
  9. C# DBHelper类 参考
  10. linux不能上网问题
  11. genymotion和adb的解决方法
  12. 利用NEST2.0 在C#中操作Elasticsearch
  13. RBAC用户角色权限设计方案【转载】
  14. Oracle Data Integrator 12cR1 (12.1.3.0.0)安装过程
  15. nginx init 官方启动脚本
  16. JavaScript中的异步操作
  17. Max Sum Plus Plus---hdu1024(动态规划求M段的最大和)
  18. 【Map,HashMap,Vector,List】资料汇总
  19. MSSQL远程连接操作(转)
  20. Qt笔记——QSqlLite

热门文章

  1. subprocess, re模块,logging, 包等使用方法
  2. opensciencegrid - GridFTP 安装
  3. 自写的简单MD5加密算法
  4. Mybatis整合Redis实现二级缓存
  5. cf 【并查集】
  6. Codeforces Round #603 (Div. 2) A. Sweet Problem 水题
  7. IT兄弟连 Java语法教程 流程控制语句 经典案例
  8. 【前端知识体系-JS相关】你真的了解JavaScript编译解析的流程吗?
  9. MySQL 表和列的注释
  10. vue-父组件和路由