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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM