Simple Conditional Routing in Reactjs

后端 未结 6 686
一整个雨季
一整个雨季 2020-11-28 05:01

How to make conditional Routing, if and only if some conditions satisfies then only routing should happen. for example, if and only if the user enters the correct credential

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 05:46

    Best way is to create a HOC. Considering you are maintaining auth state in your redux store. Or else you can check with your own variable.

    Create requireAuth.js

    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    
    export default function(ComposedComponent) {
      class Authentication extends Component {
        static contextTypes = {
          router: React.PropTypes.object
        }
    
        componentWillMount() {
          if (!this.props.authenticated) {
            this.context.router.push('/');
          }
        }
    
        componentWillUpdate(nextProps) {
          if (!nextProps.authenticated) {
            this.context.router.push('/');
          }
        }
    
        render() {
          return 
        }
      }
    
      function mapStateToProps(state) {
        return { authenticated: state.auth.authenticated };
      }
    
      return connect(mapStateToProps)(Authentication);
    }
    

    Now in the routes you can use this hoc and pass the component.

    import RequireAuth from './requireAuth';
    ...
    
    
    

提交回复
热议问题