React-在State对象中用更新或替换对象



我有一个State可变对象,包含这样的对象数组。

type State = {
Dp: ArrayDataProvider<string, Message>;
};

在Dp内部,我将有数据,这些数据将以这样的数组形式保存数据。

[{
"id": 1,
"name": "January",
"abc": abc,
"xyz": xyz
}, {
"id": 2,
"name": "February",
"abc": abc,
"xyz": xyz
}]

我想用不同的对象替换id为2的对象,我想让我的对象像这样。

[{
"id": 1,
"name": "January",
"abc": abc,
"xyz": xyz
}, {
"id": 2,
"name": "New month",
"abc": 1234abc,
"xyz": someVlaue
}]

如何在react中使用typescript以高效的方式进行操作。我做过类似的事情,但没有使用

const data = this.state.Dp?.data.slice();
const index = data.findIndex(currentItem => {
return currentItem.id === updateData[0].id;
});
data[index] = updateData;
this.state.Dp.data = data;
this.setState({ Dp: this.state.Dp });

我使用map来执行此操作:

const data = this.state.Dp?.data.map(currentItem => {
return currentItem.id === updatedItem.id ? updatedItem : currentItem;
})

map使用上一个数组中的项创建了一个新数组,但它为您提供了一个机会,可以在迭代新数组时对它们进行调整。在我的示例中,我检查项目的id,看看它是否是您想要更新的,如果id匹配,则交换您的updatedItem

老实说,我不确定TypeScript的部分。我还没有用过它。

注意-我不确定你的updateData是什么形式的,所以你可能需要调整一下。看起来你希望它是一个对象,但在你的一行中,你把它当作一个数组。

使用findIndex查找id等于2的对象的索引,然后将新对象替换到该位置。

let tempArray = [...array];
const index = tempArray.findIndex((element) => element.id === 2);
tempArray[index] = {
id: 2,
name: "New month",
abc: "1234abc",
xyz: "someVlaue"
};
setArray(tempArray);

最新更新