从零开始搭建后台--路由权限

152 阅读1分钟

路由配置 routes/admin.js

export default [
    {
        path: "/admin",
        component: Admin,
        role: 'user',       // 当前路由需要的角色权限
    }
]

权限判断 routes/AuthRoute.js


import React from 'react';
import { Route, Redirect } from 'react-router-dom';


const AuthRoute = (props) => {
    const userRole = "user";
    const {
        role: routeRole,
        backUrl,
        ...otherProps
    } = props;

    console.log(routeRole, backUrl, otherProps);


    if (userRole && userRole.indexOf(routeRole) > -1) {
        // 如果用户有权限,就渲染对应的路由
        return <Route {...otherProps} />
    } else {
        // 如果没有权限,返回配置的默认路由
        return <Redirect to={'/'} />
    }

}

export default AuthRoute;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch } from 'react-router-dom';
import reportWebVitals from './reportWebVitals';
import './index.less';
import AuthRoute from "./routes/AuthRoute";

import allPagesRoute from './routes/index';


console.log(allPagesRoute);
ReactDOM.render(
	<Router>
		<Switch>
			{
				allPagesRoute.map(
					(route) => {
						console.log('index.js', route);
						return <AuthRoute key={route.path} {...route}/>
					}
				)
			}
		</Switch>
	</Router>,
	document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();


if(module.hot){
	module.hot.accept()
  }

参考:juejin.cn/post/685705…