Sum*_*nth 14 javascript node.js reactjs next.js
我有一个模式,在打开时将哈希推送到 url example.com/#modal
,在浏览器后退按钮单击时,我想识别该事件,以便可以切换模式的状态。关键是,因为我将它与 next.js (服务器端渲染)一起使用,所以我将无法访问 window 对象(如果我错了,请纠正我)。所以我需要一种替代方法来处理浏览器后退按钮的事件。
jul*_*ves 25
您可以使用next/router
'sbeforePopState
对会话历史记录导航的更改进行操作(后退/前进操作),并确保它仅在离开当前页面时发生。
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.
Run Code Online (Sandbox Code Playgroud)
@Summy 我希望你的问题现在已经解决。如果没有,您可以尝试浏览器后退按钮:- Next.js + React 返回上一页 如果您想使用 hashbang URL,则不能使用 SSR,因为 /# 和 /#/one 是相同的路由服务器端,所以服务器无法知道要渲染什么,它需要发送一个基本模板并让客户端填充它,在这种情况下,我认为使用 CRA 或 Parcel 与 React Router 及其 HashRouter 是更好的选择,这样您将拥有一个单独的index.html,并让客户端决定渲染什么。
归档时间: |
|
查看次数: |
34130 次 |
最近记录: |