简体   繁体   English

如何使用 React-Router 6 在 React 中访问历史记录

[英]How To Access History in React With React-Router 6

I am using React-Router 6 alpha, and I would like to disable the browser "Back" button by:我正在使用 React-Router 6 alpha,我想通过以下方式禁用浏览器的“后退”按钮:

  • Detecting the back event, and检测返回事件,以及
  • On detection, using the history to immediately send the browser forward.检测到时,使用历史记录立即将浏览器转发。

In React-Router 5, this would accomplished with the following code in App.js:在 React-Router 5 中,这将通过 App.js 中的以下代码完成:

window.addEventListener("popstate", () => {
  history.go(1);
}); 

...while also using the following ...同时还使用以下内容

import { withRouter } from "react-router";

class Comp1 extends React.Component { 
    lots of stuff 
}
export default withRouter(Comp1)

The problem is... there is no withRouter , anymore.问题是......不再有withRouter了。 There's nothing to wrap the export in, and consequently no access to the history that I can see.没有什么可以包装导出,因此无法访问我可以看到的历史记录。 How can I get access to that history, if it's possible at all?如果可能的话,我如何才能访问该历史记录? I can still detect the Back button event (an alert box proves that) but I can't see how to move forward by one.我仍然可以检测到后退按钮事件(一个警告框证明了这一点),但我看不到如何向前移动一个。

(Ignore for the moment that this implementation obliterates any state held in the component-- I'm just trying to get my arms around this.) (暂时忽略此实现会消除组件中保持的任何状态——我只是想解决这个问题。)

You are correct, there isn't a withRouter Higher Order Component to inject a history prop, but there is a useNavigate hook that essentially replaces the v5 useHistory hook.你是对的,没有withRouter高阶组件来注入history道具,但有一个useNavigate钩子,它基本上取代了 v5 useHistory钩子。

useNavigate 使用导航

The useNavigate hook returns a function that lets you navigate programmatically, for example after a form is submitted. useNavigate钩子返回一个函数,让您以编程方式导航,例如在提交表单之后。

  • Pass the delta you want to go in the history stack.传递您想要进入历史堆栈的增量。 For example, navigate(-1) is equivalent to hitting the back button.例如,navigate(-1) 相当于点击后退按钮。

You can force a forward navigation with navigate(1)您可以使用navigate(1)强制向前导航

const navigate = useNavigate();

// lots of stuff

...

navigate(1);

This, of course, only works in functional components, but it would be a trivial matter to create your own HOC to wrap and pass a navigate prop to and serve much the same purpose as withRouter .当然,这仅适用于功能组件,但创建自己的 HOC 来包装和传递navigate道具并与withRouter用途withRouter相同,这将是一件微不足道的事情。

const withNavigate = WrappedComponent => props => {
  const navigate = useNavigate();

  return <WrappedComponent {...props} navigate={navigate} />;
};

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

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