在一个 reducer 内,使用新数值来更新数组中的对象,使用 Angular

huangapple go评论53阅读模式
英文:

Angular update an object in an array with new values, inside a reducer

问题

基本上,我有一个类别对象数组,其中对象的结构如下 { "categoryId": 10, "categoryName": "beverages", "description": "drinkable liquids" },在我修改类别的最后两个属性中的任何一个信息后,我希望能够更新数据。

我的代码如下:

const reducer = createReducer(
  initialCategoriesState,
  on(categoriesActions.updateCategory, (state, { data }) => ({
    ...state,
    categories: state.categories?.map((item) => (item['categoryId'] === data['categoryId'] ? data : item)),
  }))
);

但它不会更新我想要的类别,而是创建一个新的类别,其中包含本应属于需要更新的类别的新细节。

英文:

Basically, I have an array of categories objects, where an object looks like this {"categoryId":10, "categoryName":"beverages", "description": "drinkable liquids"} and after I modify the information in any of the last two attributes of the category, I want to be able update the data.

My code is:

const reducer = createReducer(
initialCategoriesState,
on(categoriesActions.updateCategory, (state, {data }) => ({
...state
categories: state.categories?.map((item) => (item['categoryId'] === data['categoryId'] ? data:item)),
}))

But it doesn't update the category that I want, it just creates a new category with the new details that were supposed to belong to the category that I must be updated

答案1

得分: 0

你可以使用对象展开语法来合并两个对象:

state.categories?.map(item => item.categoryId === data.categoryId ? {...item, ...data} : item)
英文:

You can use object spread syntax to combine two objects:

state.categories?.map(item => item.categoryId === data.categoryId ? {...item, ...data} : item)

huangapple
  • 本文由 发表于 2023年2月24日 03:14:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定