全栈开发React-私有路由

demo

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.propTypes = {
    auth: PropTypes.object.isRequired
  }
const mapStateToProps = state => ({
    auth: state.auth,
})
  export  default  connect(mapStateToProps)(PrivateRoute);

据用户的auth状态,我们将渲染Redirect或渲染组件

以下是我们PrivateRoute组件的要求

  1. 它与<Route />具有相同的API。
  2. 它呈现<Route />并将所有道具传递给它。
  3. 它检查用户是否经过身份验证,如果是,则呈现“组件”道具。如果没有,它会将用户重定向到/ login。

猜你喜欢

转载自www.cnblogs.com/guangzhou11/p/10337860.html