react的鉴权(受保护路由的实现)

react实现受保护路由的两种方式

通过高阶组件

  • 因为都是写死的,可以改造一下,抛出接口
import React, { Component } from 'react'
import {Route, withRouter} from 'react-router-dom'

import Storage from '@/utils/Storage'

class VerifyCmp extends Component {

  componentDidMount() {
  // 这里抛出一个props函数
    return Storage.get("islogin") || this.props.history.push("/login")
  }

  render() {
    const Cmp = this.props.component
    return (
      <>
        { 
          <Route path={this.props.path} render={(router) => {
            return <Cmp {...router}></Cmp>
          }}></Route>
        }
      </>
    )
  }
}

export default withRouter(VerifyCmp)

通过路由侦听

  • 都是通过类组件进行的案例,函数组件同理可以进行高阶组件和路由侦听来实现路由保护
import React, { Component } from 'react';
import RouterView from './router'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import Storage from '@/utils/storage'

@connect(state => ({
  footerMenu: state.getIn(['ck', 'footerMenu'])
}), null)
@withRouter
class App extends Component {

  constructor(props) {
    super(props);
    this.accessUri = ['/fav', '/click']
  }

	//判断是否是受保护路由 并且是否符合条件
  checkLogin(pathname) {
    const bool = this.accessUri.some(item => {
      return new RegExp(item).test(pathname)
    })
    if (bool && !Storage.get('islogin')) {
      this.props.history.push('/login')
      return;
    }
  }

  componentDidMount() {
    // console.log(this.accessUri.includes(this.props.location.pathname));
    this.checkLogin(this.props.location.pathname)

    //  总要 必须路由有侦听改变时才触发,而且第1次还不执行
    this.props.history.listen(location => {
      this.checkLogin(location.pathname)
    })
  }


  render() {
    return (
      <>
        <h3 style={{ display: this.props.footerMenu }}>aaa</h3>
        <RouterView />
      </>
    );
  }
}

export default App;

函数组件hook路由侦听的实现

const App = () => {
  const history = useHistory()

  const checkLogin = (pathname) => {
     console.log(123);
     // protectedRoute为导入的受保护路由
    const bool = protectedRoute.some(item => {
      return new RegExp(item).test(pathname)
    })
    if (bool && Storage.get('islogin') !== "") {
      history.push('/login')
    }

  }
// useEffect(effectFunc, []) 类似于 componentDidMount
// 组件第一次渲染会执行这个方法
  
  useEffect(() => {
    checkLogin("/admin")
    // 添加路由监听函数
 
    history.listen(location => {
      // 每次路由变化都会执行这个方法
      checkLogin(location.pathname)
    })
  }, [history])

  return (
    <ConfigProvider locale={zhCN}>  {/* 进入路由 */}
      <RouteList />   {/* 主路由 */}
      <AuthRoute />   {/* 受保护路由 */}
    </ConfigProvider >
  );
}

export default App;

还有一种方式,通过在axios响应拦截器中实现拦截

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaxLoongLvs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值