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

求助:react-router-dom中'useHistory'未导出的导入错误解决方法

Solution for "useHistory is not exported from 'react-router-dom'"

Why this happens

Starting from React Router v6, the useHistory hook was removed entirely and replaced with the useNavigate hook. That’s exactly why you’re hitting this import error—even though components like BrowserRouter still work (they were kept in v6 with minor adjustments), useHistory is no longer part of the library’s API.

The best approach is to update your code to use the new useNavigate hook, which serves the same purpose as useHistory but with a cleaner API. Here’s how to adjust your Login component:

import React from 'react';
import { useState, useEffect } from 'react';
// Replace useHistory with useNavigate
import { useNavigate } from 'react-router-dom';

export default function Login(){
  // Initialize navigate instead of history
  const navigate = useNavigate();
  
  // Example replacements for common history actions:
  // navigate('/dashboard'); // Same as history.push('/dashboard')
  // navigate(-1); // Same as history.goBack()
  // navigate('/login', { replace: true }); // Same as history.replace('/login')
  
  console.log(navigate);
}

Fix 2: Downgrade to React Router v5 (If you need to keep useHistory)

If you’d rather not refactor your code right now, you can downgrade to version 5.x of react-router-dom, where useHistory is still available. Run one of these commands in your project directory:

# Using npm
npm install react-router-dom@5

# Using yarn
yarn add react-router-dom@5

Once the downgrade finishes, your original code with useHistory should work without any changes.

Quick Version Check

To confirm which version of react-router-dom you’re using, run this command in your terminal:

npm list react-router-dom

This will show your current version, helping you make sure your fix matches your setup.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:32:43