从状态对象数组中删除对象元素(React.js)
我试图从数组中删除一个对象,但它总是删除最后一个对象。
const removeDuplicateHandler = (id) => {
setCopyActions((copyActions) =>
copyActions.filter((action) => action.id !== id)
);
};
这就是我正在经历的循环
{copyActions.map((actionType, idx) => (
<TargetInputBox
key={idx}
isDuplicate={true}
actionName={actionType.label}
contactPersons={store.allContactPersons}
buttonAttrValue={actionType.value}
duplicateAddHandler={() =>
addDuplicateHandler(actionType.value, actionType.label)
}
duplicateRemoveHandler={() =>
removeDuplicateHandler(actionType.id)
}
/>
))}
I am trying to remove an object from my array but it always removes the last one.
const removeDuplicateHandler = (id) => {
setCopyActions((copyActions) =>
copyActions.filter((action) => action.id !== id)
);
};
And this is the loop that Im running through
{copyActions.map((actionType, idx) => (
<TargetInputBox
key={idx}
isDuplicate={true}
actionName={actionType.label}
contactPersons={store.allContactPersons}
buttonAttrValue={actionType.value}
duplicateAddHandler={() =>
addDuplicateHandler(actionType.value, actionType.label)
}
duplicateRemoveHandler={() =>
removeDuplicateHandler(actionType.id)
}
/>
))}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
for 循环是一种更好、更有效的方法:
创建数组的副本并循环遍历它。如果程序找到与
id
相同的 ID,它将从数组中删除该索引。循环完成后,它将把状态设置为更改后的数组。A for loop is a better and more efficient way to do this:
You create a duplicate of the array and loop through it. If the program finds an ID that is the same as
id
, it will remove that index from the array. Once the loop has finished, it will set the state to the altered array.