简体   繁体   English

react-router-dom: go 在 go 返回事件的历史上两次返回

[英]react-router-dom: go back twice in history on go back event

I have three components C1, C2, C3 mapped on routes /c1 , /c2/ , /c3 .我在路由/c1/c2//c3上映射了三个组件C1、C2、C3

I want to prevent component C3 from allowing (via browser event handling) going back to C2 and instead go directly to C1 .我想阻止组件C3允许(通过浏览器事件处理)返回C2 ,而是直接返回 go 到C1

How do I achieve this?我如何实现这一目标?

This functionality is required because C2 acts as a "post-and-redirect".此功能是必需的,因为 C2 充当“post-and-redirect”。 Imagine cases where browser performs a POST operation, and when you refresh the page it asks you if you want to resubmit the form.想象一下浏览器执行 POST 操作的情况,当您刷新页面时,它会询问您是否要重新提交表单。 Well that's exactly my case.嗯,这正是我的情况。

In this case you can redirect in the flow to maintain the history stack you desire.在这种情况下,您可以在流程中重定向以维护您想要的历史堆栈。 In doing so then any back navigation (imperative/declarative from code or browser's back button) results in going back to the correct page you want the user to go back to.这样做之后,任何返回导航(来自代码或浏览器的返回按钮的命令式/声明式)都会导致返回到您希望用户返回到 go 的正确页面。

Action行动 History Stack历史堆栈 Path小路 Back Location返回位置
initial最初的 ["/"] "/" ~ ~
PUSH "/c1"推“/c1” ["/", "/c1"] "/c2" "/"
PUSH "/c1/c2"推“/c1/c2” ["/c1", "/c1/c2"] "/c1/c2" "/c1"
REPLACE "/c1/c3"替换“/c1/c3” ["/c1", "/c1/c3"] "/c1/c3" "/c1"
POP (1)流行音乐 (1) ["/c1"] "/c1" ~

To use imperative navigation in react-router-dom :要在react-router-dom中使用命令式导航:

  • v5 use the useHistory hook v5 使用useHistory钩子

    • use history.push for normal navigation使用history.push进行正常导航
    • use history.replace for redirecting使用history.replace进行重定向
    • use history.back or `history.go(-1) to go back a page使用history.back或 `history.go(-1) 到 go 返回一个页面
  • v6 use the useNavigate hook. v6 使用useNavigate挂钩。

    • use navigate(to) for normal navigation使用navigate(to)进行正常导航
    • use navigate(to, { replace: true }) for redirecting使用navigate(to, { replace: true })进行重定向
    • use navigate(-1) to go back a page使用navigate(-1)到 go 返回一个页面

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

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