Javascript 从数组中删除项(useState挂钩)
有一个像这样的useState钩子:Javascript 从数组中删除项(useState挂钩),javascript,reactjs,react-native,Javascript,Reactjs,React Native,有一个像这样的useState钩子: const [array, updateArray] = useState([]) 我知道您可以使用像这样的扩展运算符将项目添加到数组中。。(其中项目是添加的内容) 如何从该阵列中删除某些内容?假设您拥有该数组项的名称。(基于值而非索引删除) 谢谢大家! 如果您有一个对先前插入的确切值的引用(假设它存储在名为itemToRemove的变量中),您可以将其过滤掉: updateArray(array.filter(item => item !== it
const [array, updateArray] = useState([])
我知道您可以使用像这样的扩展运算符将项目添加到数组中。。(其中项目是添加的内容)
如何从该阵列中删除某些内容?假设您拥有该数组项的名称。(基于值而非索引删除)
谢谢大家! 如果您有一个对先前插入的确切值的引用(假设它存储在名为
itemToRemove
的变量中),您可以将其过滤掉:
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)
]);
}
// 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)
]);
}