首页
学习
活动
专区
圈层
工具
发布

阵列NgRx
EN

Stack Overflow用户
提问于 2022-11-18 20:24:32
回答 2查看 47关注 0票数 0
代码语言:javascript
复制
export class Ingredient {
    public name: string;
    public amount: number;

    constructor(name: string, amount: number) {
        this.name = name;
        this.amount = amount;
    }
}

我的阵列:

代码语言:javascript
复制
export const initialState2: Ingredient[] = [
  new Ingredient('Apples', 5),
  new Ingredient('Lemons', 10),
  new Ingredient('Cherries', 15),
  new Ingredient('Tangerines', 20),
  new Ingredient('Apricots', 25)
];

My NgRx Action:

代码语言:javascript
复制
export const ADD_INGREDIENT2 = createAction(
    'ADD_INGREDIENT2',
    props<{ ingredient: Ingredient }>()
);

和我的减速器:

代码语言:javascript
复制
export const shoppingListReducer = createReducer(
  initialState2,
  on(
    ShoppingListActions.ADD_INGREDIENT2,
    (state, ingredient) => ({ ...state, ingredients: [...state, ingredient] })
  )
);

我在走一条关于角的路。我想使用新的版本,新的语法,就像在这个过程中用开关/用例对旧版本所做的那样。

我有一个数组,我想工作NgRx

我希望显示数组中的元素,然后向数组中添加新元素。

但我失败了。我可能对某些类型的犯了错误。

而我在页面底部的代码是**工作**,但是我在新版本中的代码不起作用。

课程中的代码:完美地工作

代码语言:javascript
复制
export const initialState = {
  ingredients: [
    new Ingredient('Apples', 5),
    new Ingredient('Lemons', 10),
    new Ingredient('Cherries', 15),
    new Ingredient('Tangerines', 20),
    new Ingredient('Apricots', 25)
  ]
};
________________________________________________________
export const ADD_INGREDIENT = 'ADD_INGREDIENT';

export class AddIngredient implements Action {
    readonly type = ADD_INGREDIENT;
    payload: Ingredient;
}
代码语言:javascript
复制
export function shoppingListReducer(state = initialState, action: ShoppingListActions.AddIngredient) {

  switch (action.type) {
    case ShoppingListActions.ADD_INGREDIENT:
      return { ...state, ingredients: [...state.ingredients, action.payload] };
    default:
      return state;
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-11-18 20:41:49

NgRx减速器中,您应该使用破坏分配解压缩ingredient属性,并将其添加到ingredients数组中:

代码语言:javascript
复制
ingredients: [...state.ingredients, ingredient]

减速机代码:

代码语言:javascript
复制
export const shoppingListReducer = createReducer(
  initialState2,
  on(ShoppingListActions.ADD_INGREDIENT2,
    (state, { ingredient }) => ({
      ...state,
      ingredients: [...state.ingredients, ingredient],
    })
  )
);
票数 0
EN

Stack Overflow用户

发布于 2022-11-19 09:56:05

问题是你使用的是不同类型的数据。

您的状态是一个数组,由[]表示;

课程的状态是一个对象,由{}表示;

{.}表示对象和..。是为了数组。这是问题的根本原因。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74494984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档