react实现不同用户角色可访问不同的页面(路由权限管理) | 您所在的位置:网站首页 › react用户登录管理 › react实现不同用户角色可访问不同的页面(路由权限管理) |
需求:
可制定不同的角色以及对应角色可以访问的页面 实现:1.登录后根据用户角色字段获取该角色能够访问的页面路径 2.将能够访问的路径存储到全局(这里用的是localstorage) 3.在涉及权限的路由下使用自定义路由组件PrivateRoute代替Route(关于某一菜单/路径是否是需要权限的页面,可以在配置菜单数组的时候新增一个字段,值为true/false对应是否需要权限) 自定义私有路由组件 /** * 涉及权限的路由展示配置 * 有权限访问/view/profile则有权限访问/view,有权限访问/view不一定能访问/view/profile */ import React from "react"; import { Route, withRouter, RouteComponentProps } from "react-router-dom"; interface PrivateRouteProps extends RouteComponentProps { exact?: boolean; //Route组件的exact属性 path: string; //路由路径 component: React.ComponentType; //有访问权限时展示的组件 noPermissionComponent?: React.ComponentType; //没有访问权限时展示的组件 } interface PrivateRouteStates { authMenu: any[]; } class PrivateRoute extends React.Component { constructor(props) { super(props); const authMen = window.sessionStorage.getItem("authMenu"); this.state = { authMenu: JSON.parse(authMen) || [] }; } //减少不必要的更新 // shouldComponentUpdate(nextProps) { //可能存在/view/sysMng/web/portal/:catalogue形式的路径,所以不能通过此方法判断路由是否变化 // // return nextProps.path !== this.props.path // } render() { //为了用户在加入购物车时登录后可以获得最新的权限信息,故不将authMenu放在state中 const authMenu = JSON.parse(window.sessionStorage.getItem("authMenu")) || []; let accessible = authMenu.find(authpath => { return authpath.includes(this.props.path); }); if (!accessible && this.props.path.includes("/:")) { accessible = authMenu.find(authpath => { return authpath.includes(this.props.location.pathname); }); } const { exact, path, component, noPermissionComponent } = this.props; return accessible ? ( component} exact={exact} /> ) : ( noPermissionComponent ? noPermissionComponent : NoPermission} exact={exact} /> ); } } class NoPermission extends React.Component { constructor(props) { super(props); } render() { return ( textAlign: "center", padding: "0.3rem", fontSize: "0.2rem" }} > 您暂时没有权限访问此页面,如果您还未登录,请先登录;如果您已登录,可联系管理员设置权限 ); } } export default withRouter(PrivateRoute);私有路由的使用: |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |