[英]How to filter an array of Objects based on the values that are already taken?
I have an array of objects that is like:我有一个对象数组,例如:
const FirstAidTypeSource = [
{ Name: "First Aid", Value: "First Aid" },
{ Name: "Senior First Aid", Value: "Senior First Aid" },
{ Name: "Anaphylaxis Certificate", Value: "Anaphylaxis Certificate" },
{ Name: "Asthma Certificate", Value: "Asthma Certificate" }
];
and every time I use one of them I want it to be removed from the list, for example, if I create the first certificate and select "First Aid" then when I create the second certificate I don't want "First Aid" again in the list and it shouldn't be selectable, even though I found another way to do it which is working ok, but when I delete one certificate everything will mess up, for example, if I add 3 certificates and choose "First Aid" for the first one and "Senior First Aid" for the second one and so on, and then if I want to delete the first one then even though I deleted the first one which is "First Aid" and should be deleted but it is still there and also the "Add Certificate" button will disappear.并且每次我使用其中一个时,我都希望将其从列表中删除,例如,如果我创建第一个证书和 select “急救”,那么当我创建第二个证书时,我不想再次“急救”在列表中并且它不应该是可选的,即使我找到了另一种工作正常的方法,但是当我删除一个证书时,一切都会搞砸,例如,如果我添加 3 个证书并选择“急救”对于第一个,第二个是“高级急救”,依此类推,然后如果我想删除第一个,即使我删除了第一个是“急救”并且应该删除但它仍然是在那里,“添加证书”按钮也会消失。 please refer to thedemo for details
详情请参考demo
any help is appreciated in advance提前感谢任何帮助
It's because the button renders if index + 1 === formRef.current
, but formRef.current
isn't being updated when you delete a certificate.这是因为如果
index + 1 === formRef.current
按钮会呈现,但是当您删除证书时不会更新formRef.current
。
So what I did was change formRef
from a reference to a state, after making sure it's not being used a reference elsewhere.因此,我所做的是将
formRef
从对 state 的引用更改为在确保它没有在其他地方用作引用之后。 Then set up an effect hook that updates formRef
based on the length of firstAids
each time firstAids
updates.然后设置一个效果挂钩,在每次
firstAids
更新时根据firstAids
的长度更新formRef
。
useEffect(()=>{
setFormRef(firstAids.length)
}, [firstAids])
By having it as a state, the component will re-render after it's updated, and properly render the button.通过将其设置为 state,组件将在更新后重新渲染,并正确渲染按钮。
Try it out:试试看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.