Reactjs 如何根据Id从typescript中的记录中删除条目
我有一个Main.tsx文件,其中有一个记录personList,key为PersonId,value为PersonInfo,我想根据提供的Id从personList中删除一个特定条目。下面是我的代码:Reactjs 如何根据Id从typescript中的记录中删除条目,reactjs,typescript,frontend,Reactjs,Typescript,Frontend,我有一个Main.tsx文件,其中有一个记录personList,key为PersonId,value为PersonInfo,我想根据提供的Id从personList中删除一个特定条目。下面是我的代码: interface PersonInfo{ FirstName:string; SecondName:string; Age:string; } const [personList,setPersonList] = useState<Record<string,PersonInfo
interface PersonInfo{
FirstName:string;
SecondName:string;
Age:string;
}
const [personList,setPersonList] = useState<Record<string,PersonInfo>>({});
//For inserting entry
const Create = () => {
setPersonList((oldList)=>{
return {
...oldList,[PersonId]:PersonDescription //PersonDescription is of type PersonInfo
}
});
};
const Delete = () => {
const newPersonList :Record<string,PersonInfo>=
personList.filter()//Here i want to delete the entry based on personId
setPersonList(newPersonList);
};
interface PersonInfo{
名字:字符串;
第二个名称:字符串;
年龄:弦;
}
const[personList,setPersonList]=useState({});
//用于插入条目
const Create=()=>{
setPersonList((旧列表)=>{
返回{
…oldList,[PersonId]:PersonDescription//PersonDescription属于PersonInfo类型
}
});
};
常量删除=()=>{
const newPersonList:记录=
personList.filter()//这里我想删除基于personId的条目
setPersonList(新PersonList);
};
既然您已经将对象的关键点指定给了personId
,您只需执行以下操作:
constdelete=(id:string):void=>{
const filteredPersonList:Record={}
for(让输入personList){
如果(键!==id){
filteredPersonList[键]=personList[键]
}
}
setPersonList(filteredPersonList)
}
使用删除关键字怎么样
delete personList[personId];
根据记录的实际形状
,如果您真的想使用数组.prototype.filter
,那么像Object.fromEntries(Object.entries(personList).filter(([k,v])=>k!==personId))
非常感谢!你救了我的命欢迎来到Stack Overflow!我建议不要在回答中使用修辞问题。他们有可能被误解为根本没有答案。你想回答本页顶部的问题,是吗?否则请删除此帖子。