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

Hma*_*man 5 javascript arrays 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)

Dac*_*nny 1

另一种方法是串联使用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 } ])
  });
}
Run Code Online (Sandbox Code Playgroud)