简体   繁体   中英

react router v6 useNavigate vs Navigate location implementation

From what I understand, with the replacement of history in react router v6, the implementation of useNavigate() and Navigate should achieve similar behavior. How could I implement the below to function similarly to achieve return to previous page before login:

useNavigate ( https://reactrouter.com/en/v6.3.0/api#usenavigate ):

const navigate = useNavigate();
useEffect(() => {
    return navigate(-1, { replace: true }); 
});

Navigate component( https://reactrouter.com/en/v6.3.0/api#navigate ):

<Navigate to="/home" replace state={{ from: location }} />;

If I'm understanding your question correctly you are asking how to use achieve the same behavior with the navigate function as the Navigate component to redirect back to a page a user was attempting to access prior to being redirected to authenticate.

Assuming you have implemented appropriate route protection that grabs the current location being accessed and redirects to the login route with a referrer passed in state:

const location = useLocation();

 ...

<Navigate to="/login" replace state={{ from: location }} />

The login component would access the state and upon a successful authentication redirect back to the location that was passed, or a fallback/default path like the app's home page.

const location = useLocation();
const navigate = useNavigate();

...

const { from } = location.state || {};
navigate(from?.pathname || "/", { replace: true });

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