首页 > 解决方案 > 如果存在则更新对象内部的数组,否则将数组推送到对象

问题描述

如果对象当前在数组中,我想更新一些值,如果不是,我想将它添加到数组中。这是我在下面的解决方案,我认为这不是最好/正确的方法。

const handleAddToCart = product => {
  const newList = [...cart]
  if (!newList.includes(product)) {
    newList.push(product)
  } else {
    const productIndex = newList.findIndex((obj => obj._id === product._id))
    newList[productIndex].prop = "Some value"
  }
  setCart(newList)
}

谢谢你。

标签: javascriptreactjs

解决方案


你必须在这里非常小心,因为对象比较和改变状态有一些陷阱([...cart]在深度复制中是不够的cart)。您可以按如下方式以纯粹的方式更新状态,尽管我建议使用 Redux 之类的东西来进行复杂的状态管理。

const handleAddToCart = product => {
    const index = cart.findIndex(obj => obj._id === product._id)
    if (index === -1) {
        setCart(cart.concat(product))
    } else {
        setCart([
            ...cart.slice(0, index),
            Object.assign({}, product, { prop: "Some value" }),
            ...cart.slice(index + 1),
        ])
    }
}

推荐阅读