从 React-dnd 中删除一个项目

Removing an item from React-dnd

我已经创建了 my own example off of this React-dnd example 来创建拖放。我添加了一张可以使用 onRemove 函数删除卡片的卡片。即使我清除了所有对象的状态数组,我也看不到删除效果。

我的删除函数:

const handleRemove = useCallback(
(index, item) => {
  // Delete a value if found, all occurrences
  update(dustbins, {
    items: (dustbins) =>
      dustbins && dustbins.filter((arrItem) => arrItem !== item)
  });

  if (dustbins && dustbins.includes(item) && index >= 0) {
    update(dustbins, { lastDroppedItem: { $splice: [[index, 1]] } });
  }

  // Delete at a specific index, no matter what value is in it
  //   update(dustbins, { lastDroppedItem: { $splice: [[index, 1]] } });
},
[dustbins]
  );

用这种方法收到的垃圾箱经常是未定义的,但不确定为什么。这基本上没有 运行 此方法中的其余语句。 我做错了什么?

我在这里面临的另一个挑战是我可以拖放一个项目,但这个解决方案会创建重复项。我尝试使用 $splice 函数,但它不起作用,因为 Dustbin.jsx 使用 drop: onDrop, 方法来处理放置功能。如何删除重复项?

谢谢

我终于成功了。所以我可以在这里回答我自己的问题。

我正在使用 immutabilityHelper 函数 $set,它类似于普通的集合函数。

   const indexOf = useCallback(function indexOf(array, item) {
    for (var i = 0; i < array.length; i++) {
      console.log("Arr", array[i]);
      if (
        array[i].lastDroppedItem &&
        array[i].lastDroppedItem.name === item.name
      )
        return i;
    }
    return -1;
  }, []);

  const handleRemove = useCallback(
    (item) => {
      const index = indexOf(dustbins, item);
      console.log("LastDroppedItem Index", index);
      if (index < 0) return;
      setDustbins(
        update(dustbins, {
          [index]: {
            lastDroppedItem: {
              $set: null
            }
          }
        })
      );

我首先找到一个索引,然后在 index 上的 lastDroppeditem 上设置一个空值。希望它能帮助别人。 Link to the working source.