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

auth-workflow

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

posted @   全玉  阅读(775)  评论(0编辑  收藏  举报
编辑推荐:
· 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 总结
点击右上角即可分享
微信分享提示