我在更改与路由反应的视图时遇到问题。 我想为每个产品提供动态路由,网址正在更改,但页面没有重定向 这是我的 App.js 代码
import "./styles.css";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { Navbar } from "./components/Navbar";
import { Home } from "./pages/Home";
import { List } from "./pages/List";
import { Contact } from "./pages/Contact";
import { ItemDetails } from "./pages/ItemDetails";
export default function App() {
// add dynamic route to the list route below
const router = createBrowserRouter([
{
path: "/",
element: <Navbar />,
children: [
{ index: true, element: <Home /> },
{ path: "/contact", element: <Contact /> },
{
path: "/list",
element: <List />,
children: [{ path: ":id", element: <ItemDetails /> }],
},
],
},
]);
return (
<div className="App">
<RouterProvider router={router} />
</div>
);
}
然后这是我的 list.jsx
import { NavLink } from "react-router-dom";
import { items } from "../data";
export const List = () => {
return (
<div className="list page">
<h3>List page</h3>
<div className="item-list">
{items.map((i) => (
<div className="item" key={i.id}>
{/* add link to item details here */}
<NavLink to={i.id}>{i.name}</NavLink>
<img src={i.image} alt={i.name} />
</div>
))}
</div>
</div>
);
};
当导航到此网址发生变化时,预计会看到
中的路线import { useParams } from "react-router-dom";
import { itemDetailsData } from "../data";
export const ItemDetails = () => {
const { itemId } = useParams();
console.log(itemId);
const item = itemDetailsData.find((i) => i.id === itemId);
if (!item) {
return <h3> Item details not found.</h3>;
}
return (
<div className="item-details page">
<h1>{item.name}</h1>
<img src={item.image} alt={item.name} />
<ul className="specs">
{item.specs.map((spec, i) => (
<li key={i}>{spec}</li>
))}
</ul>
<p>{item.description}</p>
</div>
);
};
但不显示!
您的代码中有两个错误:
首先,您使用
children: [{ path: ":id", element: <ItemDetails /> }]
,但在 ItemDetails
中,您使用 const { itemId } = useParams();
。名称必须匹配,因此请选择 id
或 itemId
。
第二个错误是
List
缺少<Outlet />
,因此ItemDetails
永远不会显示。
如果您想在
ItemDetails
外观看List
,请使用
{
path: "/list",
element: <List />,
},
{
path: "/list/:itemId",
element: <ItemDetails />,
},