从数组中删除项目(useState挂钩)

时间:2020-09-18 01:26:05

标签: javascript reactjs react-native

具有如下所示的useState钩子:

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

我知道您可以像这样使用散布运算符将项目添加到数组中。(其中项目是要添加的内容)

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

您如何从该数组中删除内容?假设您具有该数组项的名称。 (根据价值而非指数删除)

谢谢!

1 个答案:

答案 0 :(得分:3)

如果您引用的是之前插入的确切值(例如,它存储在名为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)
  ]);
}