Mar*_*rko 7 javascript reactjs react-native
有一个 useState 钩子,如下所示:
const [array, updateArray] = useState([])
我知道您可以使用扩展运算符将项目添加到数组中,如下所示..(其中项目是要添加的内容)
updateArray(array => [...array, item])
你会如何从这个数组中删除一些东西?假设您有该数组项的名称。(根据值而不是索引删除)
谢谢你!
Cer*_*nce 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)
  ]);
}
| 归档时间: | 
 | 
| 查看次数: | 11277 次 | 
| 最近记录: |