React Router v6路由未找到问题:电商应用商品详情页跳转异常
解决React Router路由未找到问题
你的问题出在ProductCard组件中Link的路径使用了相对路径,而非绝对路径。当在/products页面点击链接时,相对路径products/${product.id}会被拼接成/products/products/${id},这与你在AllRoutes中配置的/products/:id路由规则不匹配,最终导致路由未找到错误。
修复方案
将ProductCard里所有Link的路径改为绝对路径(在路径前添加斜杠/):
修改后的ProductCard.jsx代码:
import { Rating } from "./Rating"; import { Link } from "react-router-dom"; export const ProductCard = ({ product }) => { console.log(product.id) return ( <div className="m-3 max-w-sm bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700"> <Link to={`/products/${product.id}`} className="relative"> { product.best_seller && <span className="absolute top-4 left-2 px-2 bg-orange-500 bg-opacity-90 text-white rounded">Best Seller</span>} <img className="rounded-t-lg w-full h-64" src={product.poster} alt="" /> </Link> <div className="p-5"> <Link to={`/products/${product.id}`}> <h5 className="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">{product.name}</h5> </Link> <p className="mb-3 font-normal text-gray-700 dark:text-gray-400">{product.overview}</p> <div className="flex items-center my-2"> <Rating rating={product.rating}/> </div> <p className="flex justify-between items-center"> <span className="text-2xl dark:text-gray-200"> <span>$</span><span>{product.price}</span> </span> <button className="inline-flex items-center py-2 px-3 text-sm font-medium text-center text-white bg-blue-700 rounded-lg hover:bg-blue-800">Add To Cart <i className="ml-1 bi bi-plus-lg"></i></button> {/* <button className="inline-flex items-center py-2 px-3 text-sm font-medium text-center text-white bg-red-600 rounded-lg hover:bg-red-800">Remove Item <i className="ml-1 bi bi-trash3"></i></button> */} </p> </div> </div> ) }
修改后,点击商品卡片会跳转到正确的绝对路径/products/${id},与路由配置规则匹配,即可正常渲染ProductDetail页面。
内容的提问来源于stack exchange,提问作者Tooba Jamal
相关产品推荐
相关产品推荐

