react router dom Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')

回答 3 浏览 52 2022-11-20

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;

Navbar.jsx

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;

控制台上的错误

Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')

The above error occurred in the <Router> component:

at Router (http://localhost:3000/static/js/bundle.js:39615:15) at App (http://localhost:3000/static/js/bundle.js:33:74) 

Consider adding an error boundary to your tree to customize error handling behavior. Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

krishna 提问于2022-11-20
你能分享一下你使用的是哪个版本的react-router吗?Jonathan Wieben 2022-11-20
react-router-dom 6.4 版本 @JonathanWiebenkrishna 2022-11-20
3 个回答
#1楼 已采纳
得票数 1

你可能想使用BrowserRouter,而不是Router,后者是对Router的一种包装。

Jonathan Wieben 提问于2022-11-20
同意,在导入语句中把BrowserRouter作为Router来做就可以了。Harsh Vishwakarma 2022-11-20
#2楼
得票数 1

你那里有一个错字。

<Link to="/sport"> Sports </Link>

在Route上,用 sports 拼写

<Route exact path='/sports' element={<NewsContainer key="sports" mode={mode} changeMode={changeMode} category="sports" />} />

希望它能解决这个问题。

Tomer_Ra 提问于2022-11-20
没用的,兄弟 @Tomer_Rakrishna 2022-11-20
#3楼
得票数 0

问题

你正在导入和渲染低级别的Router组件,而没有传入任何所需的props。

import { Router, Routes, Route } from "react-router-dom"

Router

declare function Router(
  props: RouterProps
): React.ReactElement | null;

interface RouterProps {
  basename?: string;
  children?: React.ReactNode;
  location: Partial<Location> | string; // <-- missing
  navigationType?: NavigationType;
  navigator: Navigator;                 // <-- missing
  static?: boolean;
}

缺少的是locationnavigator属性。这个错误特别是由于缺少location属性,它是未定义的,所以代码不能访问未定义的pathname

解决办法

你几乎不需要自己手动渲染Router。你应该转而渲染一个高级别的Router(e.g。BrowserRouterHashRouter),它实例化并维护一个历史记录引用,并将这些所需的属性传递给低层的Router组件。

例子。

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
Drew Reese 提问于2022-11-22