相关文章推荐
腼腆的西瓜  ·  React-admin - ...·  4 周前    · 
大力的荒野  ·  Getting started with ...·  4 周前    · 
追风的花生  ·  Map in React js with ...·  4 周前    · 
温柔的保温杯  ·  How to Use the ...·  4 周前    · 
奔跑的凳子  ·  Loading in Rive Files ...·  3 周前    · 
魁梧的小蝌蚪  ·  中南大学 李津臣·  1 年前    · 

usestate 数组删除

在 React Hooks 中使用 useState 管理数组,删除数组中的元素可以使用 splice() 方法或 filter() 方法。

  • splice() 方法:通过指定数组的索引位置和删除的元素个数来删除数组中的元素,并返回被删除的元素。
  • const [array, setArray] = useState([1, 2, 3, 4, 5])
    const deleteItem = (index) => {
      const newArray = [...array]
      newArray.splice(index, 1)
      setArray(newArray)
    
  • filter() 方法:通过返回布尔值 true 或 false,来决定是否保留该元素,最终返回被保留的元素组成的新数组。
  • const [array, setArray] = useState([1, 2, 3, 4, 5])
    const deleteItem = (item) => {
      const newArray = array.filter(i => i !== item)
      setArray(newArray)