React项目复用商品详情页组件及路由跳转异常问题求助
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

