Redirect page upon login using react-router-v5 and redux-toolkit

前端 未结 2 1774
庸人自扰
庸人自扰 2020-12-18 15:59

I\'m using react-router-dom v5.2.

Upon login, I want my page to redirect to /home from /. The login form is at /.

When

2条回答
  •  醉酒成梦
    2020-12-18 16:20

    Your code does not define redirection logic after login. You can do it in two way.

    1st : You can define another redirection wrapper for authentication if you want your routes to redirect in case of authentication.

    const AuthRoute = ({ component: Component, ...rest }) => {
      const authState = useSelector(selectorAuth)
      const location = useLocation()
      return (
         {
            if (!authState.isUserLoggedIn) {
              return 
            } else {
              return (
                
              )
            }
          }}
        />
      )
    }
    
    const App = () => {
      return (
        
          
    // It is for login users to redirect to home page "404 Not found."} />
    ) }

    2nd : Another approach can be imperatively handling with history.push() or history.replace() :

    const Layout = () => {
      const authState = useSelector(selectorAuth);
      const history = useHistory();
    
      useEffect(() => {
        // if isUserLoggedIn turned to true redirect to /home
        if (authState.isUserLoggedIn) { 
          history.push("/home");
        }
      }, [authState.isUserLoggedIn]); // triggers when isUserLoggedIn changes
    
      return (
        
          
          
          
           "404 Not found."} />
        
      );
    };
    
    const App = () => {
      return (
        
          
    ); };

    Why didn't your code work? Take a look at the code below :

          
          
          
           "404 Not found."} />
    

    What it does? It checks your browser path and check if it matches with given Route rule from top to down. If Route path matches then it renders the component if not it continues through down visiting each one of Route until it matches your 404.

    So back to your case; when you login, you were not leaving "/" path. Because there is no logic implemented to leave the "/" path. So it again match with landing page even though it is authenticated. It matches with route path (Landing page) and stays there. It does not continue and try your logic on ProtectedRoute.

提交回复
热议问题