【问题标题】:using .find() method to find productId as a parameter base on the productId click使用 .find() 方法根据 productId click 查找 productId 作为参数
【发布时间】:2021-05-26 11:51:08
【问题描述】:

现在,我在 match.params.id 获取 productId,但是当我使用 find 方法比较 item.id 和 match.params.id 时,它返回未找到产品....下面是代码

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,但我的函数声明中不存在任何内容

【问题讨论】:

    标签: javascript reactjs url parameters


    【解决方案1】:

    这是因为从路由中检索到的 id 类型为 string。因为你在做=== strict equals find 会失败。

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

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

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

    let { id } = useParams();
    

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2017-02-23
      • 1970-01-01
      • 2013-12-15
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多