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

React Router:查询参数变化时阻止触发unstable_usePrompt

解决React Router v6.8.1中查询参数变化触发离开提示的问题

要实现仅在路由路径(不含查询参数)变化且有未保存更改时触发离开提示,可以通过unstable_useBlocker替代unstable_usePrompt来实现更精准的控制——因为unstable_useBlocker能直接获取到即将跳转的目标路由信息,而unstable_usePrompt的when参数无法动态获取下一路由。

具体实现代码

import { useLocation, unstable_useBlocker as useBlocker } from 'react-router-dom';

function YourFormComponent() {
  // 获取当前路由的路径(不含查询参数)
  const currentLocation = useLocation();
  // 你的未保存更改判断函数
  const hasUnsavedChanges = didValuesChange();

  useBlocker((navigationTx) => {
    // 判断下一路由的路径是否和当前一致(仅查询参数变化时pathname相同)
    const isSameRoute = navigationTx.nextLocation.pathname === currentLocation.pathname;

    // 无未保存更改 或 仅查询参数变化,直接允许跳转
    if (!hasUnsavedChanges || isSameRoute) {
      navigationTx.proceed();
      return;
    }

    // 有未保存更改且路径变化,弹出确认提示
    const confirmLeave = window.confirm(
      "Are you sure you want to navigate away from this page? You have some unsaved changes!"
    );

    confirmLeave ? navigationTx.proceed() : navigationTx.cancel();
  });

  // 组件其余逻辑...
  return <div>/* 你的表单内容 */</div>;
}

关键逻辑说明

  1. useLocation:获取当前路由的pathname(即不含查询参数的核心路由路径)。
  2. unstable_useBlocker:接收一个回调函数,参数navigationTx包含即将跳转的nextLocation对象,通过对比nextLocation.pathname和当前pathname,判断是否是同一路由的查询参数变化。
  3. 跳转控制:仅在「有未保存更改」且「路由路径确实变化」时,才弹出确认提示,用户确认后允许跳转,否则取消导航。

关于useNavigation的说明

你之前尝试用useNavigation获取下一路由,但该API的location属性仅在导航过程中存在,未触发导航时为undefined,因此不适合用来判断即将跳转的路由信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:50:22