简体   繁体   中英

Redirect logged user from login/register page with React Hooks

I would like to handle behavior when logged user will try to access login/register/any related view, to redirect such request to homepage, using react-hooks. I've tried something like this, on top of my login form component:

  useEffect(() => {
  if (isAuthenticated) history.push("/dashboard");
     }, [isAuthenticated, history]);

But every time logged user clicks on login, he/she sees login form for glimpse of and eye and I would like to prevent it. As a workaround, I've come with NotLoggedRoute , which mimics PrivateRoute behavior, but I'm not sure if this is the best way to handle it such way:

import React from "react";
import { Route, useHistory } from "react-router-dom";
import { useSelector } from "react-redux";

export const NotLoggedRoute = ({ component: Component, ...rest }) => {
  const isLogged = useSelector(state => state.user.isLogged);
  const history = useHistory();

  return (
    <Route {...rest} render={props =>
    isLogged ?  history.push("/home") :<Component {...props} />
    }
    />
  );
};

I'm using react-router-dom v5.1.2, react 16.9 and react-redux 7.2.0

Basically your direction is correct but you can leverage here Redirect component from react-router-dom and children prop - define PublicRoute which handle the logic and wrap all your public components with it:

PublicRoute Component:

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { useSelector } from 'react-redux';

const PublicRoute = ({ children, ...rest }) => {
    const isLogged = useSelector(state => state.user.isLogged);

    return (
        <Route
            {...rest}
            render={() => {
                if (isLogged) {
                    return <Redirect to="/home" />;
                }

                return children;
            }}
        />
    );
};

export default PublicRoute;

use:


<PublicRoute path="/login">
   <Login />
</PublicRoute>

<PublicRoute path="/register">
   <Register />
</PublicRoute>

etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM