如何通过单击按钮从反应状态挂钩数组中删除对象 [英] How to delete objects from react state hook array with a button click

查看:96
本文介绍了如何通过单击按钮从反应状态挂钩数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个按钮,该按钮根据传递的索引从数组(状态)中删除对象,我已经尝试了很多,但是我的方法都不起作用:(,所以代码和希望我能找到帮助的人:

I'm trying to make a button that deleted an object from an array (which is the state) depending on the passed index, I've tried alot but none of my ways worked :( , so this is the code and hope i can find someone to help:

状态:

const [items, setItems] = useState([{ name: "", quantity: "", unit: "" }]);

删除函数:

const deleteItem = (i) => {
    const newItems = [...items]
    newItems.splice(i, 1)
    setItems(newItems)
}

jsx元素:

    {
        items.map((item, i) => {
            return (
                <div key={i} className={`mt3 item-input-wrapper`}>
                    <div>some other els here</div>
                    <button onClick={() => deleteItem(i)} >delete item</button>
                </div>
            )
        })
    }


推荐答案

您可以使用过滤器

const deleteItem = (i) => {
  setItems(currentItems => currentItems.filter((item, index) => index !== i));
}

尽管如此,您可能会使用更常量来访问项目,例如ID。

Altho you'd probably use smth more constant for accessing an item, like an id.

这篇关于如何通过单击按钮从反应状态挂钩数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆