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

运行项目时出现react-router-dom中useHistory未找到报错咨询

解决React Router v6中useHistory未找到的问题

问题原因

React Router从v6版本开始移除了useHistory钩子,改用useNavigate钩子替代,这就是你遇到导出错误的直接原因。

解决步骤

  1. 替换导入语句
    将原有导入:

    import { useHistory } from 'react-router-dom';
    

    替换为:

    import { useNavigate } from 'react-router-dom';
    
  2. 调整钩子使用逻辑

    • 原useHistory用法:
      const history = useHistory();
      history.push('/target-path');
      history.replace('/target-path');
      history.goBack();
      
    • 替换为useNavigate后的写法:
      const navigate = useNavigate();
      // 对应history.push
      navigate('/target-path');
      // 对应history.replace
      navigate('/target-path', { replace: true });
      // 对应history.goBack
      navigate(-1);
      // 对应history.goForward
      navigate(1);
      

特殊场景处理

如果项目依赖的第三方库仍在使用useHistory,无法直接升级到v6,可选择两种方案:

  • 降级React Router至v5版本,继续使用useHistory
  • 给第三方库提交适配v6的代码更新,或等待官方适配版本发布

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:43:20