You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目复用商品详情页组件及路由跳转异常问题求助

Fixing the Product Detail Route Navigation Issue

The problem you're facing comes down to two key things: using a relative path in your Link component and a slight typo in the route name. Here's how to fix it and avoid needing a new component:

Why It's Going to the Wrong Path

When you use a path without a leading slash (like product-details/${data.productId}), React Router treats it as a relative path. Since your ShopLiked component is likely rendered under the /shop-liked route, the link appends the relative path to the current URL, resulting in /shop-liked/product-details/:productId. Additionally, your existing product detail route is /product-detail/:productId (singular "detail"), but your link uses "product-details" (plural)—that's a mismatch.

Corrected Code

Update your Link component to use an absolute path that matches your existing route:

<Grid key={data.productId} item xs={6}>
  <Link to={`/product-detail/${data.productId}`}>
    <MainCards data={data}/>
  </Link>
</Grid>

Do You Need a New Component?

No, you don't need to develop a new component! By using the absolute path /product-detail/:productId, you're directing users to your existing product detail page component. This component will receive the productId param via React Router (just like it does from other product list components), so all your existing logic for displaying product details will work as expected.

Quick Check

Make sure your router configuration has the existing route set up correctly, similar to this example:

<Routes>
  {/* ... other routes ... */}
  <Route path="/product-detail/:productId" element={<ProductDetail />} />
  <Route path="/shop-liked" element={<ShopLiked />} />
</Routes>

This ensures that when users click the link, they're routed directly to your already-built ProductDetail component with the correct product ID.

内容的提问来源于stack exchange,提问作者aditya kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:42:54