react 路由权限配置,例子
时间: 2023-08-23 16:29:24 浏览: 58
好的,下面是一个基于React Router的路由权限控制示例,假设我们有一个需要登录并且具有管理员权限才能访问的Dashboard页面:
首先,在App.js中定义路由:
```javascript
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import Login from './Login';
import Dashboard from './Dashboard';
function App() {
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<PrivateRoute path="/dashboard" roles={['admin']} component={Dashboard} />
</Switch>
</Router>
);
}
```
其中,PrivateRoute是我们自定义的一个组件,用于检查用户是否登录并具有相应的角色,如果未登录或角色不匹配则重定向到登录页面:
```javascript
import { Route, Redirect } from 'react-router-dom';
function PrivateRoute({ component: Component, roles, ...rest }) {
return (
<Route
{...rest}
render={(props) =>
isAuthenticated() && hasRole(roles) ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
);
}
function isAuthenticated() {
// 判断用户是否已登录,这里只是一个示例
return localStorage.getItem('token') !== null;
}
function hasRole(roles) {
// 判断用户是否具有相应的角色,这里只是一个示例
const userRoles = localStorage.getItem('roles');
return roles.some((r) => userRoles.indexOf(r) >= 0);
}
```
这样,在访问Dashboard页面时,就会自动检查用户是否登录并具有管理员角色,如果未登录或角色不匹配则重定向到登录页面。如果已登录并且具有管理员角色,则显示Dashboard页面。
通过这种方式,我们可以在React应用程序中实现更复杂的路由权限控制。当然,具体的实现方式会因应用场景和需求而有所不同。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)