简体   繁体   English

如何通过单击按钮从反应状态挂钩数组中删除对象

[英]How to delete objects from react state hook array with a button click

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:我正在尝试制作一个按钮,根据传递的索引从数组(这是状态)中删除一个对象,我尝试了很多,但我的方法都不起作用:(,所以这是代码,希望我可以找人帮忙:

state:状态:

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

deleting function:删除功能:

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

jsx elements: 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>
            )
        })
    }

You can do it with filter :你可以用filter做到这一点:

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

Altho you'd probably use smth more constant for accessing an item, like an id.尽管您可能会使用更常量来访问项目,例如 id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM