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

React Router Dom报错:Cannot read properties of undefined(reading 'pathname')

解决react-router-dom中"无法读取未定义属性'pathname'"错误

在使用react-router-dom开发React应用时,控制台抛出如下错误:

未捕获类型错误:无法读取未定义属性(读取'pathname')
错误发生在<Router>组件中:
at Router (http://localhost:3000/static/js/bundle.js:39615:15)
at App (http://localhost:3000/static/js/bundle.js:33:74)

相关代码

App.jsx

import { useState } from 'react';
import './App.css';
import NewsContainer from './Components/NewsContainer';
import { Router, Routes, Route } from "react-router-dom"

function App() {
  const [mode, setMode] = useState("light")

  const changeMode = () => {
    if (mode === "light") {
      setMode("dark")
      document.body.style.backgroundColor = "rgb(30 41 59)"
    } else {
      setMode("light")
      document.body.style.backgroundColor = "white"
    }
  }

  return (
    <Router>
      <div className='justify-evenly'>
        <Routes>
          <Route exact path="/" element={<NewsContainer key="general" mode={mode} changeMode={changeMode} category="general" />} />
          <Route exact path='/sports' element={<NewsContainer key="sports" mode={mode} changeMode={changeMode} category="sports" />} />
          <Route exact path='/buisness' element={<NewsContainer key="buisness" mode={mode} changeMode={changeMode} category="buisness" />} />
          <Route exact path='/entertainment' element={<NewsContainer key="entertainment" mode={mode} changeMode={changeMode} category="entertainment" />} />
          <Route exact path='/health' element={<NewsContainer key="health" mode={mode} changeMode={changeMode} category="health" />} />
        </Routes>
      </div>
    </Router>
  );
}

export default App;
import { Link } from "react-router-dom";

function Navbar({ mode, changeMode }) {
  return (
    <div
      className={`${mode === "light" ? "bg-gray-100" : "dark : bg-slate-900"} `}
    >
      <header className="text-gray-600 body-font">
        <div className="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center">
          <li
            className={`flex title-font font-medium list-none items-center text-${
              mode === "light " ? "gray-900" : "white"
            } mb-4 md:mb-0 cursor-pointer`}
          >
            <span
              className={`ml-3 text-xl text-${
                mode === "light" ? "black" : "white"
              }`}
            >
              <Link to="/">Hind News</Link>
            </span>
          </li>
          <nav className="md:mr-auto md:ml-4 md:py-1 md:pl-4 md:border-l md:border-gray-400 flex flex-wrap items-center text-base justify-center list-none cursor-pointer">
            <li
              className={`mr-5 hover:text-${
                mode === "light" ? "dark : gray-900" : "white"
              }`}
            >
              <Link to="/sport"> Sports </Link>
            </li>
            <li
              className={`mr-5 hover:text-${
                mode === "light" ? "dark : gray-900" : "white"
              }`}
            >
              <Link to="/buisness">Buisness </Link>
            </li>
            <li
              className={`mr-5 hover:text-${
                mode === "light" ? " dark:gray-900" : "white"
              }`}
            >
              <Link to="/entertainment">Entertainment </Link>
            </li>
            <li
              className={`mr-5 hover:text-${
                mode === "light" ? "dark : gray-900" : "white"
              }`}
            >
              <Link to="/health">Health </Link>
            </li>
          </nav>
          <input
            type="text"
            className="inline-flex items-center bg-gray-200 border-0 py-1 px-3 focus:outline-none hover:bg-gray-300 rounded text-base mt-4 md:mt-0"
          />
          <button className="inline-flex items-center bg-gray-100 border-0 py-1 px-3 focus:outline-none hover:bg-gray-200 rounded text-base mt-4 md:mt-0">
            Search
            <svg
              fill="none"
              stroke="currentColor"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="2"
              className="w-4 h-4 ml-1"
              viewBox="0 0 24 24"
            >
              <path d="M5 12h14M12 5l7 7-7 7"></path>
            </svg>
          </button>
          <div className="flex justify-center">
            <div className="flex justify-center">
              <div className="form-check form-switch">
                <input
                  className="form-check-input appearance-none w-9 -ml-10 rounded-full float-left h-5 align-top bg-white bg-no-repeat bg-contain bg-gray-300 focus:outline-none cursor-pointer shadow-sm ml-60"
                  type="checkbox"
                  role="switch"
                  id="flexSwitchCheckDefault"
                  onClick={changeMode}
                />
                <label
                  className={`form-check-label inline-block text-${
                    mode === "light" ? "gray-900" : "white"
                  } `}
                  htmlFor="flexSwitchCheckDefault"
                >
                  {" "}
                  Switch Mode
                </label>
              </div>
            </div>
          </div>
        </div>
      </header>
    </div>
  );
}

export default Navbar;

错误原因及解决方法

这个错误的核心原因是:在react-router-dom v6及以上版本中,Router是底层组件,必须接收history对象作为props才能正常工作。直接使用Router而不传入history对象,会导致它无法读取pathname属性(内部依赖history对象的location.pathname)。

核心修复步骤

  1. 替换路由组件:改用web场景下的高层路由组件BrowserRouter,将其别名设为Router,这样无需修改后续代码结构:
// 替换App.jsx中的导入语句
import { BrowserRouter as Router, Routes, Route } from "react-router-dom"
  1. 修正路由路径不一致问题:Navbar中<Link to="/sport">的路径少了s,和App.jsx中定义的/sports不匹配,修改为:
<Link to="/sports"> Sports </Link>
  1. 修正样式类名错误:Navbar中存在类名空格问题,比如dark : bg-slate-900应改为dark:bg-slate-900,mode === "light "多了空格应改为mode === "light",否则样式无法正常切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:25:34