Sup,
所以我有了这个对象:
data: {
OtherFields: {},
Skills: [
{
id: Math.random(),
name: 'Default Category',
skills: [],
},
],
{
所以技能数组是非常动态的,我需要添加类别,每个类别都有自己的名为技能的数组,其中会填充其他对象,默认类别就在那里。
而里面的技能将有:
{
id: Math.random(),
skillName: 'Default Category',
}
我想做的是用id类别动态地将技能添加到特定类别中,因为我们不知道用户会添加多少。
这里我做了什么,直到现在:
const handleAdd = (id, content) => {
// id is the cateogry of that specific cateogry that im receiving from input
// content is the value of the input
// this is the object i need to push into the category
const newItem = {
id: Math.random(),
skillName: content,
};
// and then update it,
const newData = data.Skills.find((i) => i.id === id);
console.log(newData)
newData.skills.push(newItem);
setData({ ...data, Skills: [...data.Skills, newData] });
//this it works but adds another cateogry and doesnt not replace the current one with the new value that is added
};
这会将newData
附加到数组:
Skills: [...data.Skills, newData]
但它在追加时不会从数组中过滤出相同的记录;整个数组加上这个新元素";。即使该元素在概念上是的重复,代码也不知道这一点。(见鬼,即使引用的是重复的,也没有什么能阻止数组包含对同一对象的两个引用。)
听起来你想过滤整个数组以在重新附加之前删除该元素。例如:
Skills: [...data.Skills.filter(s => s.id !== newData.id), newData]
由于您正在修改原始对象,所以这应该可以工作,请重命名变量以使其更易于读取。
还要考虑不要更改原始对象。
setData({ ...data, Skills: [...data.Skills] });