想要使用 next.js 为浏览器的后退按钮提供事件处理程序 [英] Want to have an event handler for the browser's back button with next.js
问题描述
我有一个模式,它在打开时将哈希推送到 url example.com/#modal
,在浏览器后退按钮单击时,我想识别该事件,以便我可以切换状态模态的.关键是,由于我将它与 next.js(服务器端渲染)一起使用,我将无法访问窗口对象(如果我错了,请纠正我).所以我需要另一种方法来处理浏览器后退按钮的事件.
I am having a modal which while opening pushes a hash to url example.com/#modal
, on browser back button click, I want to recognise that event so that I can toggle the state of modal. the point is, since Im using it with next.js (server side rendering), I will not be having access to window object (correct me if I am wrong). so I need an alternate way to handle the event of browser back button.
推荐答案
添加到 Artinium's answer 用一个实际的例子对于您的情况,您可以使用 next/router
的 beforePopState
对会话历史导航的更改(后退/前进操作)采取行动,并确保仅在离开当前页面时才会发生.
To add to Artinium's answer with a pratical example for your case, you can use next/router
's beforePopState
to act on changes to the session history navigation (back/forward actions), and make sure it'll only happen when leaving the current page.
useEffect(() => {
router.beforePopState(({ as }) => {
if (as !== router.asPath) {
// Will run when leaving the current page; on back/forward actions
// Add your logic here, like toggling the modal state
}
return true;
});
return () => {
router.beforePopState(() => true);
};
}, [router]); // Add any state variables to dependencies array if needed.
这篇关于想要使用 next.js 为浏览器的后退按钮提供事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!