限制后退按钮反应路由器

时间:2020-07-09 03:07:56

标签: reactjs react-router react-hooks

我想限制对路由器的访问并禁用后退按钮。

例如,如果用户手动在浏览器选项卡上键入或单击event/:eventId以外的URL,我想将其重定向到event/:eventId

当前:

  1. 用户访问了event/1234/friends
  2. 它被重定向到event/1234
  3. 用户单击后退按钮并能够看到event/1234/friends。 (它应该不能能够访问event/1234/friends)。

注意:此错误仅在移动设备上发生。您无法在桌面上复制它。

所需:

  1. 用户访问了event/1234/friends
  2. 它被重定向到event/1234
  3. 禁用后退按钮,或者如果用户单击后退按钮,将无法访问event/1234/friends

这是我的代码的样子

 const eventPathname = props.history?.location?.pathname;
  const matches = eventPathname.match(/^\/event\/([^/]+)\/.+$/);
  if (!!matches) {
    const defaultPathname = `/event/${matches[1]}`;
    props.history.length = 1;
    window.location.replace(defaultPathname);
    props.history.push(defaultPathname);
  }

这是一个代码沙箱:

https://codesandbox.io/s/keen-silence-47ztr

请记住,您不能在台式机上复制它,而只能在移动设备上复制。

我在StackOverflow上检查了多个线程,例如1234,但找不到正确的答案。我如何实现此目标的任何帮助?

1 个答案:

答案 0 :(得分:1)

您可以简单地使用history.replace(而不是推送)

if (!!matches) {
    const defaultPathname = `/event/${matches[1]}`;
    //props.history.length = 1; //<---- probably not required
    //window.location.replace(defaultPathname); //<---- not required
    props.history.replace(defaultPathname); //<---- like this
  }

修改:一些说明

push和replace之间的主要区别是push会在浏览器的历史记录中创建一个新条目,而replace只会替换当前状态。这样,您将无法找到启用后退按钮。

一些参考

1

2

3

4