未捕获的类型错误:无法读取未定义的属性(读取‘路径名’):如何解决这个路由器问题?
2022-01-13
5841
"react": "^17.0.2", "react-dom": "^17.0.2", "react-router-dom": "5.2.0",
这是我的 App.js 文件
import React from "react"
import Navbar from "./components/Navbar"
import Main from "./components/Main"
import Details from "./components/Details"
import { BrowserRouter as Switch, Router, Route, Link } from "react-router-dom"
export default function App() {
return (
<Router>
<div className="container">
<header>
<ul>
<li><Link to="/navbar">Navbar</Link></li>
<li><Link to="/main">Home</Link></li>
<li><Link to="/details">Details</Link></li>
</ul>
<div>
<Switch>
<Route exact path="/navbar" component={Navbar} />
<Route exact path="/main" component={Main}/>
<Route exact path="/details" component={Details}/>
</Switch>
</div>
</header>
</div>
</Router>
)
}
1个回答
仅浏览一下您共享的代码 仅 ,您就把导入弄得一团糟。
import { BrowserRouter as Switch, Router, Route, Link } from "react-router-dom";
您已将
BrowserRouter
导入为
Switch
。我确定您打算将其导入为
Router
,并单独导入
Switch
。
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
问题是您正在渲染两个路由器,但它们不共享它们提供的路由上下文。换句话说,“Router”处理来自链接的导航,但
Route
组件从嵌套的
BrowserRouter
(又称“Switch”)获取其路由上下文。
如果这不能完全解决您的问题,那么我们可能需要查看更多相关代码。不过,请先尝试上述操作,以使您的
App
组件正常工作。
Drew Reese
2022-01-13