React route v4路由鉴权
React route v4中没有vue的beforeEach的功能,可以用以下两种思路,来做路由鉴权:
1. Route组件的render中鉴权
定义AuthRoute组件
import React from 'react' import PropTypes from 'prop-types' import { Route, Redirect } from 'react-router-dom' const AuthRoute = ({ component: Component, authenticated, redirectTo, ...rest}) => { return ( <Route {...rest} render={props => ( authenticated ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: redirectTo, state: { from: props.location } }} /> ) )} /> ) } AuthRoute.propTypes = { authenticated: PropTypes.bool, redirectTo: PropTypes.string.isRequired, component: PropTypes.func.isRequired, } AuthRoute.defaultProps = { authenticated: false, } export default AuthRoute
使用AuthRoute组件
import React, { Component } from 'react' import { AuthRoute } from 'react-router-auth' import UserProfile from './UserProfile' class Example extends Component { render () { return ( <AuthRoute path="/profile" component={UserProfile} redirectTo="/login" authenticated={this.props.authenticated} /> ) } }
类似实现的线上demo
2. history的listen方法中鉴权
// 加入对history的监听 this.props.history.listen((location, action) => { // 执行内容, 第一个参数是当前的location, 第二个是此次执行的动作 console.log(action, location.pathname, location.state) })
要使用React router提供的history对象,可以从props中取到,不要使用自己定义的history对象,否则,监听Link跳转无效
参考:https://github.com/joelseq/react-router-auth
https://reactrouter.com/web/example/auth-workflow
https://www.zhihu.com/question/66731068
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-09-01 javascript Date 总结