首页 > 解决方案 > ReactJS: replacing object from array with new value replaces whole array

问题描述

I have array selectedItems and when I try to update existing object:

i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 1}] 

to:

i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 3}]

It replaces the whole array with:

 [ { lable: "two", uniqueId: 3 }]

how can I avoid that?

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
      }]
    }))
  }
}

标签: javascriptarraysreactjs

解决方案


另一种方法是串联使用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 } ])
  });
}

推荐阅读