在组件状态下添加和删除对象
我有一个检查输入的列表,当它们被选中并取消选择时,我将尝试将它们从状态添加/删除。但是我注意到当我取消选择一个时,我先前选择的是从状态中删除的对象。我认为这是因为当称为Onchange功能时,状态尚未更新(尽管UI已有),但是我不明白如何将所选择的所有支票的完整列表列出,而状态落后于一个值。这是我的输入和onchange func:
const [selected, setSelected] = useState([]);
const handleSelect = (e) =>
!!DATA &&
DATA.forEach((item, idx) => {
let name = e.target.name;
if (item.payerName === name && !selected.includes(item)) {
setSelected([...selected, item]);
return;
} else if (item.payerName === name && selected.includes(item)) {
// index varies
let index = selected.indexOf(item);
let clean = selected.splice(index, 1);
setSelected(clean);
}
});
DATA.map((item, idx) => {
return(
<input
name={item.payerName}
type="checkbox"
checked={selected.includes(item)}
onChange={handleSelect}
className="insurance-checkbox m-2 mt-3"
/>
)
}
I have a list of check inputs, and when they are selected and deselected I am trying to add/remove them from the state. But Ive noticed when I deselect one the one I selected prior is the object removed from the state. I think this is because when the onChange function is called the state hasnt updated (although the UI has) but I dont understand how to have a full list of all the checks selected with the state lagging behind one value. Heres my input and onChange func:
const [selected, setSelected] = useState([]);
const handleSelect = (e) =>
!!DATA &&
DATA.forEach((item, idx) => {
let name = e.target.name;
if (item.payerName === name && !selected.includes(item)) {
setSelected([...selected, item]);
return;
} else if (item.payerName === name && selected.includes(item)) {
// index varies
let index = selected.indexOf(item);
let clean = selected.splice(index, 1);
setSelected(clean);
}
});
DATA.map((item, idx) => {
return(
<input
name={item.payerName}
type="checkbox"
checked={selected.includes(item)}
onChange={handleSelect}
className="insurance-checkbox m-2 mt-3"
/>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
或者更好:
Try this:
or even better: