我刚刚开始学习 React,并被这个错误卡住了



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

我已经搜索了这个问题很多,到处我得到的答案是使用来代替href,但我已经使用到

这是我的代码app.js
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router-dom";
return (
<>
<Navbar
title="Texter"
aboutus="AboutTextUtils"
toggleMode={toggleMode}
mode={mode}
></Navbar>
<BrowserRouter>
<Routes>
<Route path="/about" element={<About />} />
<Route
path="/"
element= {<Text title="Enter the text below" mode={mode}/>} 
/> 
</Routes>
</BrowserRouter>
</>

这个导航栏的链接标签是

import { Link, Router } from 'react-router-dom';
export default function Navbar(props) {
return (
<Router>
<nav className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}>
<div className="container-fluid">
<a className="navbar-brand" href="/">{props.title}</a>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<Link className="nav-link active" aria-current="page" to={"/"}>Home</Link>  //This is the Link tag
</li>
<li className="nav-item">
<Link  className="nav-link" to={"/about"}>{props.aboutus}</Link>  //This is the Link tag
</li>
</ul>
<div className={`form-check form-switch text-${props.mode === 'light'?'dark':'light'}`}>
<input className="form-check-input" onClick={props.toggleMode} type="checkbox" role="switch" id="flexSwitchCheckDefault"/>
<label className="form-check-label" htmlFor="flexSwitchCheckDefault">Enable Dark Mode</label>
</div>
</div>
</div>
</nav>
</Router>
)

Issue

您正在渲染BrowserRouter之外的Navbar组件,然后将NavbarUI渲染为具有一些所需道具的低层Router组件。

看到路由器

declare function Router(
props: RouterProps
): React.ReactElement | null;
interface RouterProps {
basename?: string;
children?: React.ReactNode;
location: Partial<Location> | string; // <-- required!!
navigationType?: NavigationType;
navigator: Navigator;                 // <-- required!!
static?: boolean;
}

location是未定义的,不能访问任何pathname属性。

<标题>

解决方案移动Navbar组件BrowserRouter,所以有一个提供的路由器上下文。删除Navbar中的Router

import { Link } from 'react-router-dom';
export default function Navbar(props) {
return (
<nav className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}>
...
</nav>
);
}
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router-dom";
...
return (
<>
<BrowserRouter>
<Navbar
title="Texter"
aboutus="AboutTextUtils"
toggleMode={toggleMode}
mode={mode}
/>
<Routes>
<Route path="/about" element={<About />} />
<Route
path="/"
element={<Text title="Enter the text below" mode={mode} />}
/> 
</Routes>
</BrowserRouter>
</>
);

相关内容

  • 没有找到相关文章

最新更新