简体   繁体   English

防止转到浏览器后退按钮上的上一页

[英]Prevent going to the previous page on browser back button

I have a Next.js / React.js project I'm working on and I'm trying to redirect to a certain page when browser's back button is clicked.我有一个正在处理的 Next.js / React.js 项目,我试图在单击浏览器的后退按钮时重定向到某个页面。 My approach is as follows我的做法如下

useEffect(() => {
    Router?.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            handleRouteChange({ toHref: getRoutingPath('HOME') }, Router.push);
        }
        return true;
    });
        
    return () => {
        Router?.beforePopState(() => true);
    };
}, [dispatch, router]);

And this code works.这段代码有效。 When I click the back button, it takes me to the home page as intended.当我单击后退按钮时,它会按预期将我带到主页。

But the issue is, when I click on the back button, it takes me to the previous page for a second and then redirects to the home page.但问题是,当我单击后退按钮时,它会将我带到上一页一秒钟,然后重定向到主页。 How can I prevent going to the previous page at all?我怎样才能完全阻止转到上一页?

You can return false from the beforePopState callback to disable Next.js handling the routing automatically and handle it yourself.您可以从beforePopState回调返回false以禁用 Next.js 自动处理路由并自行处理。

From the router.beforePopState documentation:来自router.beforePopState文档:

If cb returns false , the Next.js router will not handle popstate , and you'll be responsible for handling it in that case.如果cb返回false , Next.js 路由器将不会处理popstate ,在这种情况下您将负责处理它。 See Disabling file-system routing .请参阅禁用文件系统路由

useEffect(() => {
    router.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            handleRouteChange({ toHref: getRoutingPath('HOME') }, Router.push);
            return false;
        }
        return true;
    });
    
    return () => {
        router.beforePopState(() => true);
    };
}, [router]);

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

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