从数组中删除项目(useState Hook)

7

使用useState钩子如下:

const [array, updateArray] = useState([])

我知道你可以使用展开运算符像这样将项目添加到数组中..(其中item是要添加的内容)

updateArray(array => [...array, item])

如果你有数组项的名称,你要如何从这个数组中删除它?(按值而非索引进行删除)

谢谢!

1个回答

14

如果你有对之前插入的确切值的引用(比如它存储在一个名为itemToRemove的变量中),那么可以使用 .filter 将其过滤掉:

updateArray(array.filter(item => item !== itemToRemove));

这适用于原始值和对象,但将一个对象的确切引用保留在当前状态中是非常奇怪的。对于对象,通常你会需要找出一种方法来确定状态中元素的索引,可能是通过唯一属性上的 findIndex 方法,之后你将把新状态设置为不包括该索引的数组,类似下面的示例:

// say that the array contains objects with a unique 'id' property
// and you need to remove the item with the id of idToRemove
const index = array.findIndex(({ id }) => id === idToRemove);
if (index !== -1) {
  updateArray([
    ...array.slice(0, index),
    ...array.slice(index + 1)
  ]);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接