React router private routes / redirect not working

后端 未结 9 1252
轮回少年
轮回少年 2020-12-07 16:57

I have slightly adjusted the React Router example for the private routes to play nice with Redux, but no components are rendered when Linking or Redirecting to other \'pages

9条回答
  •  时光取名叫无心
    2020-12-07 17:21

    I have struggled with this issue as well, and here is my solution.

    Instead of passing isAuthenticated to every < PrivateRoute> component, you just need to get isAuthenticated from state in < PrivateRoute> itself.

    import React from 'react';
    import {Route, Redirect, withRouter} from 'react-router-dom';
    import {connect} from 'react-redux';
    
    // isAuthenticated is passed as prop here
    const PrivateRoute = ({component: Component, isAuthenticated , ...rest}) => {
        return  {
                    return isAuthenticated ?
                        (
                            
                        )
                        :
                        (
                            
                        )
                }
            }
        />
    };
    
    const mapStateToProps = state => (
        {
            // isAuthenticated  value is get from here
            isAuthenticated : state.auth.isAuthenticated 
        }
    );
    
    export default withRouter(connect(
        mapStateToProps, null, null, {pure: false}
    )(PrivateRoute));
    

提交回复
热议问题