小编Hma*_*man的帖子

ReactJS:用新值替换数组中的对象将替换整个数组

我有数组selectedItems,当我尝试更新现有对象时:

i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 1}] 
Run Code Online (Sandbox Code Playgroud)

至:

i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 3}]
Run Code Online (Sandbox Code Playgroud)

它将整个数组替换为:

 [ { lable: "two", uniqueId: 3 }]
Run Code Online (Sandbox Code Playgroud)

我该如何避免呢?

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
      }]
    })) …
Run Code Online (Sandbox Code Playgroud)

javascript arrays reactjs

5
推荐指数
1
解决办法
118
查看次数

标签 统计

arrays ×1

javascript ×1

reactjs ×1