使用 .find() 方法根据 productId click 查找 productId 作为参数

using .find() method to find productId as a parameter base on the productId click

现在,我正在 match.params.id 处获取 productId,但是当我使用查找方法比较 item.id 和 match.params.id 时,它 return 找不到产品.. ..下面是代码

const DetailsPage = (props) => {
    console.log(props.match.params.id)
    const product = data.products.find((item) => item.id === props.match.params.id)
    console.log(product);
    if (!product) {
        return (
            <h1>Product Not Found</h1>
        )
    }
    return (
        <div>
            DetailsPage
                {product.name}
        </div>
    )

如您所见,我 console.log(props.match.params.id) 为我提供了产品参数 ID,但我的函数声明中不存在任何内容

这是因为从路由中检索到的 ID 类型为 string。由于您正在执行 === 严格等于查找将失败。

您可以将 params.id 类型转换为 Number

const product = data.products.find((item) => item.id === Number(props.match.params.id))

另外 react-router 现在提供 useParams 挂钩来检索参数。

let { id } = useParams();