需求:
可制定不同的角色以及对应角色可以访问的页面
实现:
1.登录后根据用户角色字段获取该角色能够访问的页面路径 2.将能够访问的路径存储到全局(这里用的是localstorage) 3.在涉及权限的路由下使用自定义路由组件PrivateRoute代替Route(关于某一菜单/路径是否是需要权限的页面,可以在配置菜单数组的时候新增一个字段,值为true/false对应是否需要权限)
自定义私有路由组件
import React from "react";
import { Route, withRouter, RouteComponentProps } from "react-router-dom";
interface PrivateRouteProps extends RouteComponentProps {
exact?: boolean;
path: string;
component: React.ComponentType;
noPermissionComponent?: React.ComponentType;
}
interface PrivateRouteStates {
authMenu: any[];
}
class PrivateRoute extends React.Component<
PrivateRouteProps,
PrivateRouteStates
> {
constructor(props) {
super(props);
const authMen = window.sessionStorage.getItem("authMenu");
this.state = {
authMenu: JSON.parse(authMen) || []
};
}
render() {
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 ? (
<Route path={path} component={component} exact={exact} />
) : (
<Route
path={path}
component={noPermissionComponent ? noPermissionComponent : NoPermission}
exact={exact}
/>
);
}
}
class NoPermission extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div
style={{ textAlign: "center", padding: "0.3rem", fontSize: "0.2rem" }}
>
您暂时没有权限访问此页面,如果您还未登录,请先登录;如果您已登录,可联系管理员设置权限
</div>
);
}
}
export default withRouter(PrivateRoute);
私有路由的使用:
|