next/router beforePopState未触发

zd287kbt  于 2022-12-12  发布在  其他
关注(0)|答案(1)|浏览(116)

根据标题,当我点击后退按钮时,beforePopState没有启动。
根据文档,此代码是_app.js中调用的挂钩。
下一个版本是12.1.5
有人知道问题出在哪里吗?

import { useEffect } from 'react';
import { type NextRouter, useRouter } from 'next/router';

const pushCurrentUrl = (url: string): void => {
  history.pushState({}, '', url);
};

export const useInterceptRouting = (): NextRouter => {
  const router = useRouter();

  useEffect(() => {
    router.events.on('routeChangeComplete', pushCurrentUrl);

    const beforePopState = (): void => {
      console.log('beforePopState');
    };

    router.beforePopState(() => {
      beforePopState();
      return false;
    });

    return () => {
      router.events.off('routeChangeComplete', pushCurrentUrl);
    };
  }, []);

  return router;
};
8wtpewkr

8wtpewkr1#

我放弃了依赖下一个路由器的想法,转而使用完全原生的浏览器。请记住,浏览器对所有这些的实际支持都是flacky。

const handleWindowClose = (event: BeforeUnloadEvent): string => {
  event.preventDefault();
  event.returnValue = dict.leaveCallConfirmation;
  return dict.leaveCallConfirmation;
};

export const redirectTo = (url: string): void => {
  window.removeEventListener('beforeunload', handleWindowClose);

  window.location.replace(url);
};

export const interceptRoutingChange = (): void => {
  window.addEventListener('beforeunload', handleWindowClose);
};

然后在_app文件中调用interceptRoutingChange()
当您希望重定向用户而不打开确认警报时,请使用redirectTo

相关问题