React-Router使用中出现Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')错误的解决方法
解决React Router中"Cannot read properties of undefined (reading 'pathname')"错误
嘿,我一眼就发现问题所在啦!你遇到的这个报错,根源是用错了路由组件。
问题原因
在react-router-dom v6版本中,Router是一个底层基础组件,它要求你手动传入一个history对象来管理路由状态。但你直接使用了<Router>却没有提供这个必要的history对象,组件内部尝试读取history.location.pathname时,就会因为history是undefined而抛出这个错误。
快速解决方案
你需要用BrowserRouter替代Router——这是react-router-dom封装好的路由组件,它会自动创建并管理history对象,不需要你手动配置。
修改你的app.js中的导入语句:
// 原来的导入 import { Routes, Route, Router, Link } from 'react-router-dom'; // 修改为 import { Routes, Route, BrowserRouter as Router, Link } from 'react-router-dom';
这样<Router>就会自动使用BrowserRouter的功能,不会再出现找不到pathname的问题了。
额外小提醒
我注意到你的App组件里使用了mode、toggleMode、alert、showAlert这些变量,但没有在组件内声明对应的状态。记得补上这些useState定义哦,不然运行时还会出现其他错误,比如:
function App() { // 补上状态定义 const [mode, setMode] = useState('light'); const [alert, setAlert] = useState(null); const toggleMode = () => { // 你的主题切换逻辑 }; const showAlert = (message, type) => { // 你的提示框逻辑 }; // 剩下的渲染代码... }
修改后的完整App.js示例
import React, { useState } from "react"; import "./App.css"; import Navbar from "./component/Navbar"; import TextForm from "./component/TextForm"; import Alert from "./component/Alert"; import About from "./component/About"; import { Routes, Route, BrowserRouter as Router, Link } from 'react-router-dom'; function App() { const [mode, setMode] = useState('light'); const [alert, setAlert] = useState(null); const toggleMode = () => { if(mode === 'light'){ setMode('dark'); document.body.style.backgroundColor = '#042743'; showAlert("Dark mode has been enabled", "success"); } else { setMode('light'); document.body.style.backgroundColor = 'white'; showAlert("Light mode has been enabled", "success"); } }; const showAlert = (message, type) => { setAlert({ msg: message, type: type }); setTimeout(() => { setAlert(null); }, 1500); }; return ( <> <Router> <Navbar title="TextUtils" aboutText="About TextUtils" mode={mode} toggleMode={toggleMode} /> <Alert alert={alert} /> <div className="container my-3"> <Routes> <Route path="/about" element={<About />} /> <Route path="/" element={<TextForm heading="Enter text to analyze" mode={mode} showAlert={showAlert} />} /> </Routes> </div> </Router> </> ); } export default App;
内容的提问来源于stack exchange,提问作者Monali chaki
相关产品推荐
相关产品推荐

