[英]Add unique object into array reactjs
i have problem here, when i click into one element 2 times it will add 2 time into my array, i dont know how to add unique element into array, can u guys help me?我这里有问题,当我点击一个元素 2 次时,它会在我的数组中添加 2 次,我不知道如何将唯一元素添加到数组中,你们能帮帮我吗? Thank you guys
感谢你们
const handleClick = (
id: number,
name: string | null,
avatar: string | null
) => {
setListChoose((prevState: any) =>
[...prevState].concat({ id, name, avatar })
);
};
You can check that whether that contact exists in array or not.您可以检查该联系人是否存在于数组中。 If not then append in list else don't.
如果不是,则附加在列表中,否则不要。
const handleClick = (
id: number,
name: string | null,
avatar: string | null
) => {
let list = Array.from(listChoose); //assuming that list name is listChoose.
if(list.find(l => l.id === id) === undefined){
setListChoose((prevState: any) =>
[...prevState].concat({ id, name, avatar })
);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.