求助:react-router-dom中'useHistory'未导出的导入错误解决方法
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.
Fix 1: Switch to useNavigate (Recommended for v6)
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

