简体   繁体   English

react router v6 useNavigate vs Navigate location 实现

[英]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.据我了解,随着 react router v6 中历史记录的替换,useNavigate() 和 Navigate 的实现应该实现类似的行为。 How could I implement the below to function similarly to achieve return to previous page before login:我怎样才能在 function 中实现以下类似的实现登录前返回上一页:

useNavigate ( https://reactrouter.com/en/v6.3.0/api#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 ):导航组件( 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.如果我正确理解您的问题,您是在询问如何使用navigate function 作为Navigate组件来实现相同的行为,以重定向回用户在被重定向以进行身份验证之前尝试访问的页面。

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:假设您已经实施了适当的路由保护,该保护获取当前正在访问的位置并使用 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.登录组件将访问 state 并在成功的身份验证后重定向通过的位置,或应用程序主页等后备/默认路径。

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

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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