我想限制对路由器的访问并禁用后退按钮。
例如,如果用户手动在浏览器选项卡上键入或单击event/:eventId
以外的URL,我想将其重定向到event/:eventId
当前:
event/1234/friends
。event/1234
event/1234/friends
。 (它应该不能能够访问event/1234/friends
)。注意:此错误仅在移动设备上发生。您无法在桌面上复制它。
所需:
event/1234/friends
。event/1234
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
请记住,您不能在台式机上复制它,而只能在移动设备上复制。
答案 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
只会替换当前状态。这样,您将无法找到启用后退按钮。
一些参考: