zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    BZOJ3413: 匹配
    BZOJ5084: hashit
    BZOJ2281: [Sdoi2011]黑白棋
    BZOJ4808: 马
    BZOJ3208: 花神的秒题计划Ⅰ
    BZOJ3714: [PA2014]Kuglarz
    BZOJ2102: [Usaco2010 Dec]The Trough Game
    JZOJ6676. 【2020.06.01省选模拟】查拉图斯特拉如是说 (第二类斯特林数+多项式多点求值)
    LOJ #3217. 「PA 2019」Desant(状压dp)
    JZOJ 5154.【NOI2017模拟6.20】树形图求和 (矩阵树定理)
  • 原文地址:https://www.cnblogs.com/mengff/p/13594977.html
Copyright © 2011-2022 走看看