You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中beforePopState点击返回按钮不触发问题求助

Next.js 12.1.5中beforePopState点击返回不触发的问题解决

问题根源

你手动调用了history.pushState(),这会干扰Next.js自身的路由状态管理机制。Next.js的beforePopState是基于它自己维护的路由栈来触发的,手动修改浏览器history栈会导致Next.js无法正确识别pop事件,自然不会触发beforePopState回调。

解决方案

  1. 移除手动调用history.pushState的代码,让Next.js自行管理路由状态,不要直接操作浏览器的history API。
  2. 给beforePopState添加清理逻辑,避免组件卸载后残留监听引发潜在问题,同时确保useEffect依赖数组包含router,适配路由实例更新场景。

修改后的代码

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

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

  useEffect(() => {
    const beforePopStateHandler = () => {
      console.log('beforePopState');
      return false;
    };

    // 注册beforePopState监听
    router.beforePopState(beforePopStateHandler);

    return () => {
      // 清理监听,恢复默认行为
      router.beforePopState(() => true);
    };
  }, [router]);

  return router;
};

补充说明

Next.js的beforePopState仅在用户触发浏览器前进/后退按钮,或调用router.back()/router.forward()这类官方路由方法时触发,直接操作浏览器history栈的行为不会被它识别。

内容的提问来源于stack exchange,提问作者Bolza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:45:55