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

升级react-router后history模块Transition类型缺失问题求助

解决方案:react-router 6.11.1中替代history.Transition类型的方案

问题原因

升级react-router/react-router-dom到6.11.1后,依赖的history库版本同步更新,原Transition类型已被移除,替换为Navigation类型,两者核心功能一致,仅命名和部分内部结构做了调整。

具体修复步骤

  1. 替换类型导入
    移除原import { Transition } from 'history',改为导入Navigation类型:

    import { Navigation } from 'history';
    
  2. 替换代码中所有Transition类型引用

    • 将状态定义中的Transition改为Navigation:
      const [lastLocation, setLastLocation] = useState<Navigation>();
      
    • 将block方法的参数类型从Transition改为Navigation:
      const unblock = navigator.block((tx: Navigation) => {
        // 原有逻辑保持不变
      });
      

修改后的完整代码片段

import { Navigation } from 'history';
import { useEffect, useState } from 'react';
import { useHistory } from './useHistory';
import { useLocation, useNavigate } from 'react-router';

type Return<T> = {
  setObjectChashed: (input: T) => void;
};

export function useWarnOnLeaveUnsaved<T extends { id: string | null }>(
  objectCached: T,
  saveFunction: () => Promise<void | null>
): Return<T> {
  const navigate = useNavigate();
  const location = useLocation();
  const [lastLocation, setLastLocation] = useState<Navigation>();
  const [doNavigation, setDoNavigation] = useState(false);
  const [cashed, setCashed] = useState<string | null>(null);

  const navigator = useHistory();

  useEffect(() => {
    if (doNavigation && lastLocation) {
      navigate(lastLocation.location.pathname);
    }
  }, [doNavigation, lastLocation]);

  useEffect(() => {
    if (!hasChanges()) return;

    const unblock = navigator.block((tx: Navigation) => {
      const autoUnblockingTx = {
        ...tx,
        retry() {
          unblock();
          tx.retry();
        },
      };
      handleBlockedNavigation(autoUnblockingTx);
    });
    return unblock;
  }, [navigator, handleBlockedNavigation]);

  // 补充原代码缺失的辅助函数示例
  function hasChanges() {
    return cashed !== JSON.stringify(objectCached);
  }

  function handleBlockedNavigation(tx: Navigation) {
    if (window.confirm('有未保存的修改,确定要离开吗?')) {
      tx.retry();
    }
  }

  return {
    setObjectChashed: (input) => setCashed(JSON.stringify(input))
  };
}

额外说明

  • Navigation类型包含原Transition的核心属性:location(目标导航位置)、retry()(继续执行导航的方法),完全兼容原有逻辑。
  • 若你封装的useHistory是基于react-router的useNavigate,也可以直接使用react-router提供的useNavigation钩子,其block方法的参数类型同样为Navigation。

内容的提问来源于stack exchange,提问作者Lukas M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:57:34