我在代码中找不到我的错误。有人可以向我解释一下。
测试:Nav:' 应该呈现在路径“/”上。 “Home”组件应仅在路径“/”上呈现 “Home”组件不应显示在任何其他路由中 路由“/product/:id”应仅显示组件 ProductDetail' 路由“/products/ create 应该只显示 CreateProduct 组件”感谢您的帮助
我的代码:
import { Route, useParams } from 'react-router-dom';
import CreateProduct from './components/CreateProduct/CreateProduct.jsx';
import ProductDetail from './components/ProductDetail/ProductDetail.jsx';
import Home from './components/Home/Home.jsx';
import Nav from './components/Nav/Nav.jsx';function App() {
return (
<div className="App">
<Nav />
<Route exact path='/' render={Home} />
<Route exact path='/product/:Id' render={ProductDetail} />
<Route exact path='/products/create' render={CreateProduct} />
</div>
);
}
回答1
第一件事你需要用浏览器路由器包装你的 routes ,如果你使用的是 V6 则不需要使用
“精确的”
V6 见这个 https://reactrouter.com/docs/en/v6/getting-started/tutorial
回答2
我认为你应该用 <Routes>
包装你的 routes
回答3
将你的路由标签包裹在 routes 和 BrowseRouter 中,也可以根据你使用的 react-router 版本使用元素而不是渲染。
还可以尝试在 Home 和 ProductDetail 等其他组件中使用 nav 组件,以便该组件仅包含路由,使事情变得更简单一些。