0

我有一个对象数组就是这种格式

sampleItemDetail: [
    {
      type: 'Take out the garbage',
      isBox1: true
    },
    {
      type: 'Watch my favorite show',
      isBox1: true
    },
    {
      type: 'Charge my phone',
      isBox2: true
    },
    {
      type: 'Cook dinner',
      isBox1: true
    },
    {
      type: 'Take out the garbage1',
      isBox2: true
    },
    {
      type: 'Watch my favorite show2',
      isBox1: true
    },
    {
      type: 'Charge my phone3',
      isBox1: true
    }
]

我正在使用 react-beautiful-dnd 拖放这个对象数组。我希望能够基于拖放以及 isBox 标志来分配索引。这样做最有效的方法是什么。我很困惑,因为该州没有索引。我是否需要向元素添加索引属性才能做到这一点?

https://codesandbox.io/s/react-beautiful-dnd-tutorial-forked-ij1oq?file=/src/index.js

4

1 回答 1

0

假设 items 数组的大小始终为 3,您可以尝试此操作:

// Create a local shallow copy of the state
var items = this.state.items.slice()

// Find the index of the selected item within the current items array.
var selectedItemName = this.state.selected;
function isSelectedItem(element, index, array) {
    return element.id === selectedItemName;
};
var selectedIdx = items.findIndex(isSelectedItem);

// Extract that item
var selectedItem = items[selectedIdx];

// Delete the item from the items array
items.splice(selectedIdx, 1);

// Sort the items that are left over
items.sort(function(a, b) {
    return a.id < b.id ? -1 : 1;
});

// Insert the selected item back into the array
items.splice(1, 0, selectedItem);

// Set the state to the new array
this.setState({items: items});
于 2020-08-26T14:28:07.563 回答