react路由权限设置


参考:https://tylermcginnis.com/react-router-protected-routes-authentication/ 解决路由私有方法
创建PrivateRoute.js文件
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
    <Route
        {...rest}
        render={props => auth.isAuthenticated === true ? <Component {...props} /> : <Redirect to='/login' />}
    />
)

PrivateRoute.prototype = {
    auth: PropTypes.object.isRequired
}
//redux 拿取判别登陆状态的值
const mapStateToProps = state => ({
    auth: state.auth
})

export default connect(mapStateToProps, {})(PrivateRoute)

使用方式

//私有路由配置
import PrivateRoute from './common/PrivateRoute'


//需要授权的页面
 <Switch>
                <PrivateRoute path="/xxx" component={xxx} exact />
  </Switch>

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM