【发布时间】:2020-01-16 22:07:02
【问题描述】:
我有数组selectedItems,当我尝试更新现有对象时:
i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 1}]
到:
i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 3}]
它将整个数组替换为:
[ { lable: "two", uniqueId: 3 }]
我怎样才能避免这种情况?
handleChange = (label, uniqueId) => {
const { selectedItems } = this.state
const findExistingItem = selectedItems.find((item) => {
return item.uniqueId === uniqueId;
})
if(findExistingItem) {
selectedItems.splice(findExistingItem);
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
} else {
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
}
}
【问题讨论】:
-
find返回项目...那么,您认为selectedItems.splice(findExistingItem)会做什么?提示:什么都没有 - 你会想要const findExistingItem = selectedItems.findIndex(.....和if(findExistingItem >= 0)...或if(~findExistingItem) -
@JaromandaX 对。我必须指出我在哪里找到了 uniqueId 但无法用新的替换。我试过
splice和slice。我应该用什么代替拼接 -
实际上,这也不行,因为“uniqueId”是相同的,所以可以有多个......属性名称的奇怪选择,因为它不是唯一的
-
@JaromandaX 是的,我可能应该将其更改为更合适的内容。谢谢指出
-
你怎么打电话给
handleChange?这些论点是什么意思?
标签: javascript arrays reactjs