react-router 5.0 的鉴权
2024-10-01 10:23:50
react-router 5.0 的鉴权
当我们使用react-router 控制页面的路由时候,有些页面,是需要登录才能访问,有些不需要登录就可以访问,还有些页面,是根据用户的权限来限制访问的。
如果是传统的多页面,只需要后端鉴权就可以了,没权限就直接后端重定向。
但是单页面情况下,路由使用了 window.history.statepush 这种情况下,路由的改变,是不会向服务器发送页面请求的。所以需要前端来鉴权。
一、参考vue的办法
在vue 里面 路由配置为 json 格式,所以很方便的使用 路由守卫 , 来控制权限。所以网上有一种办法,就是利用 react-router-config 来模仿 vue的路由鉴权。
其源码也不复杂。详细使用可以参考 。 通过研究以后发现,这似乎并不能满足我的要求,因为嵌套的子路由好像没有办法一次解决,也就是说,每个页面的嵌套子路由,要单独的配置json。并且似乎无法在父页面里面,对子页面的组件传props。
二、自己写一个类似的 Route 组件,并在其里面鉴权
新建一个 RouteGuard.tsx 源码如下。
import * as React from 'react';
import { Route, Redirect } from 'react-router-dom'; // interface GuardProps {
// path:string;
// component:React.Component;
// permissions?:any[];
// exact?:boolean|undefined;
// strict?:boolean|undefined;
// otherProps?:object;
// } // 可以由mobx注入用户信息
class Guard extends React.Component<any, any> {
constructor(props: any) {
super(props);
// 假设这里从 mobx 里面拿到了用户信息
const userinfo = {
level: 1 // 假设等级是一般用户
};
// 如果用户信息不存在,则需要去登录
let auth = true;
if (!userinfo) {
auth = false;
} else if (this.props.permissions) {
// 如果存在,说明是需要区别等级鉴权的
const permissions = this.props.permissions;
if (permissions.indexOf(userinfo.level) === -1) {
auth = false;
}
}
this.state = {
auth
};
}
public render() {
const ComponentPage = this.props.component;
return (
<Route
path={this.props.path}
exact={this.props.exact || false}
strict={this.props.strict || false}
render={props => {
return (
this.state.auth ? (
<ComponentPage {...props} {...this.props.otherProps} />
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
) )
}
}
/>
);
}
}
export default Guard;
使用方式与 Rute 类似,只要在需要鉴权的页面,使用RouteGuard 组件就可以了,如果不需要鉴权的,依然可以继续使用原生的 route 组件:
import * as React from 'react';
import { Switch } from 'react-router-dom';
import RouteGuard from "src/RouteGuard";
import Index from "src/pages/main/Index/Index"; class Home extends React.Component<any>{
public componentDidMount(){
console.log(this.props);
}
public render() {
return (
<div className="_Home">
<div className="section base-container">
<Switch>
<RouteGuard path="" exact={true} component={Index} />
</Switch>
</div>
</div>
);
}
} export default Home;
总结:还可以继续加入一些判断,例如移动端和PC端的区别,来渲染不同的组件
最新文章
- Eclipse中启用Oracle jdbc logging
- Python框架、库以及软件资源汇总
- 基于注解配置的Spring MVC 简单的HelloWorld实例应用
- escape()、encodeURI()、encodeURIComponent()区别详解
- 哈希(Hask)
- mvc checked=\";checked\";
- xubuntu手记
- ios webview 图片自适应屏幕宽度
- Quartz.Net任务调度框架
- 动态代理与AOP
- Oracle中wm_concat()的使用方法
- 海尔的U+智慧生活操作系统
- rpc和websocket的区别
- Java学习之IO字节流
- static类成员(变量和函数)
- 计算机学院大学生程序设计竞赛(2015’12) 1009 The Magic Tower
- JAVA基础--工厂模式
- hdu1151有向图的最小顶点覆盖
- The ways to kill Oracle session
- C#自定义FTP访问类的代码
热门文章
- LUA upvalues
- SSM框架的配置Spring+Springmvc +Mybatis
- 通俗易懂的Redis数据结构基础教程
- Coherent Calculator
- ASP程序中调用Now()总显示“上午”和“下午”,如何解决?
- C# 可扩展编程MEF学习
- 【423】COMP9024 Revision
- 123457123456#0#-----com.twoapp.drawGame09--前拼后广--儿童画画游戏jiemei
- js下利用userData实现客户端保存表单数据
- Swift学习 (一)