React router v4 - Authorized routes with HOC

前端 未结 2 2045
清歌不尽
清歌不尽 2020-12-20 02:27

I have a problem to prevent unauthorized users from accessing authorized-only routes/components - such as logged in users dashboard

I have the following code:

<
2条回答
  •  余生分开走
    2020-12-20 02:32

    Since you are using React Router 4, the answer by Matthew Barbara, while absolutely correct, is unnecessarily complicated. With RR4 you can simply use the Redirect component to handle your redirects. See https://reacttraining.com/react-router/web/api/Redirect for more info.

    import React, { Component } from "react";
    import { connect } from "react-redux";
    import { Redirect } from "react-router-dom";
    
    export default function requireAuth (WrappedComponent) {
    
      class Authentication extends Component {
    
        render () {
    
          if (!this.props.authenticated) {
            return 
          }
    
          return 
        }
      }
    
      function mapStateToProps (state) {
        return { authenticated: state.authenticated }
      }
    
      return connect(mapStateToProps)(Authentication);
    }
    

提交回复
热议问题