javascript - 如果存在则更新对象内部的数组,否则将数组推送到对象
问题描述
如果对象当前在数组中,我想更新一些值,如果不是,我想将它添加到数组中。这是我在下面的解决方案,我认为这不是最好/正确的方法。
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)
}
谢谢你。
解决方案
你必须在这里非常小心,因为对象比较和改变状态有一些陷阱([...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),
])
}
}
推荐阅读
- javascript - localStorage 不更新 Django
- php - 如何在MYSQL中组合不同的数据
- dialogflow-es - Ngrok url 每天都会更改我启动 Ngrok
- rust - 在结构内的向量内改变结构
- cpu-architecture - D触发器如何帮助稳定下面的电路?
- php - 向 magento-backend-stores 添加子菜单
- html - safari的css变换旋转
- java - Google OCR 边界多边形
- flutter - Flutter & Navigator & ImagePicker : 为什么我可以进入下一页?查找已停用小部件的祖先是不安全的
- swift - 从 Xcode 提交时遇到问题