我正在尝试制作一个按钮,根据传递的索引从数组(这是状态)中删除一个对象,我已经尝试了很多但我的方法都没有奏效:(,所以这是代码和希望我能找到人帮忙:
状态:
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>
)
})
}
最佳答案
你可以用 filter
来做到这一点:
const deleteItem = (i) => {
setItems(currentItems => currentItems.filter((item, index) => index !== i));
}
虽然您可能会使用更常量来访问项目,例如 id。
关于javascript - 如何通过单击按钮从 react 状态 Hook 数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60977463/