如何从state中删除数组元素?附现有products数组代码示例
React 从state中删除数组指定元素操作方法
核心注意点:React的state遵循不可变原则,禁止直接修改原数组(例如使用splice、pop等直接改动原数组的方法),必须传入全新的数组触发组件重渲染
最常用的实现方案是通过filter方法生成过滤后的新数组,再更新到state中,示例如下:
函数组件(useState场景)
import { useState } from 'react'; // 初始化state,把你现有的products数组传入 const [products, setProducts] = useState([ { id: 1, name: "Jr.Henry", command: "Seni takip etmeye başladı", img: require("../../assets/imgs/batman-icon.png"), follow: false, time: "23 dakika", follower: 0 }, { id: 2, name: "Artsy", command: "Oy verdi", img: require("../../assets/imgs/batman-icon.png"), follow: false, time: "23 dakika", follower: 0 }, ]); // 按id删除指定元素的方法 const deleteProductById = (targetId) => { // filter会返回全新的数组,不会改动原state const filteredProducts = products.filter(item => item.id !== targetId); setProducts(filteredProducts); } // 调用示例:删除id为1的元素 // deleteProductById(1)
类组件场景
import React from 'react'; class ProductList extends React.Component { constructor(props) { super(props); this.state = { products: [ { id: 1, name: "Jr.Henry", command: "Seni takip etmeye başladı", img: require("../../assets/imgs/batman-icon.png"), follow: false, time: "23 dakika", follower: 0 }, { id: 2, name: "Artsy", command: "Oy verdi", img: require("../../assets/imgs/batman-icon.png"), follow: false, time: "23 dakika", follower: 0 }, ] } } deleteProductById = (targetId) => { const filteredProducts = this.state.products.filter(item => item.id !== targetId); this.setState({ products: filteredProducts }) } }
按数组下标删除的实现
如果需要根据元素的下标位置删除,调整filter的判断逻辑即可:
const deleteProductByIndex = (targetIndex) => { const filteredProducts = products.filter((item, index) => index !== targetIndex); setProducts(filteredProducts); }
内容的提问来源于stack exchange,提问作者doğan kısa
相关产品推荐
相关产品推荐

