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

标签 javascript arrays reactjs

我有数组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
      }]
    }))
  }
}

最佳答案

另一种方法是串联使用 Array#filterArray#concat 函数,其中;

  • uniqueId 不匹配的项目将被过滤掉。这将替换您当前解决方案的 find() 逻辑,然后是,
  • 调用 concat() 方法将新的“替换项”附加到过滤后的数组的末尾

在可以这样实现的代码中:

handleChange = (label, uniqueId) => {
  const {
    selectedItems
  } = this.state

  this.setState({
    selectedItems : selectedItems
      /* Filter any existing item matching on uniqueId */
      .filter(item => (item.uniqueId !== uniqueId))
      /* Append replacement { label, uniqueId } to state array */
      .concat([ { label, uniqueId } ])
  });
}

关于javascript - ReactJS:用新值替换数组中的对象替换整个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57950591/

相关文章:

javascript - jQuery Ajax 下拉菜单数量

javascript - Jquery,切片失败时返回什么?

c++ - 访问 2D 结构时程序崩溃

C 程序 : converting an if statement code to a code which does not use logical, 关系运算符或选择结构(允许 NO 开关)

javascript - react .js : Non-CSS animations

javascript - 预期语法错误 : Unexpected token, }

javascript - 使用FineUploader,我可以用指定文件夹中的文件预先填充上传区域吗?

c - 在c中用相同的数字初始化数组会导致不同的值

javascript - react : get DOM position for one of the children of component

javascript - 为什么我的队列可以正常工作而不会出列?