Redirect to previous path on login - React Router v4

后端 未结 4 604
时光取名叫无心
时光取名叫无心 2020-12-31 02:51

I am using react router v4 and trying to implement a functionality where no matter what route the user clicks on, he gets taken to the login page i.e. if he is not logged in

4条回答
  •  甜味超标
    2020-12-31 03:12

    Previous answers are not detail enough.

    Solution:

    Router

    
      
        {publicRouteList()}
        
        {getLoggedRouteList(state.logged)}
        
      
    
    

    getLoggedRouteList

    const getLoggedRouteList = (logged) => {
      if (!logged) {
        return (
           {
              return (
                
              );
            }}
          />
        );
      }
    
      const output = [];
      output.push(
        /* Here place route list that need logged */
      );
      return output;
    }
    

    Login Component

    class Login extends React.Component {
      login = async param => {
        const { location } = this.props;
        const { state } = location;
    
        /* Here place request login api */
    
        // go to state.from if set before
        if (state && state.from) {
          history.replace(state.from);
        }
        // else go to home
        else {
          history.replace('/');
        }
      }
    }
    

提交回复
热议问题