export class Ingredient {
public name: string;
public amount: number;
constructor(name: string, amount: number) {
this.name = name;
this.amount = amount;
}
}我的阵列:
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:
export const ADD_INGREDIENT2 = createAction(
'ADD_INGREDIENT2',
props<{ ingredient: Ingredient }>()
);和我的减速器:
export const shoppingListReducer = createReducer(
initialState2,
on(
ShoppingListActions.ADD_INGREDIENT2,
(state, ingredient) => ({ ...state, ingredients: [...state, ingredient] })
)
);我在走一条关于角的路。我想使用新的版本,新的语法,就像在这个过程中用开关/用例对旧版本所做的那样。
我有一个数组,我想工作NgRx。
我希望显示数组中的元素,然后向数组中添加新元素。
但我失败了。我可能对某些类型的犯了错误。
而我在页面底部的代码是**工作**,但是我在新版本中的代码不起作用。
课程中的代码:完美地工作
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;
}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;
}
}发布于 2022-11-18 20:41:49
在NgRx减速器中,您应该使用破坏分配解压缩ingredient属性,并将其添加到ingredients数组中:
ingredients: [...state.ingredients, ingredient]减速机代码:
export const shoppingListReducer = createReducer(
initialState2,
on(ShoppingListActions.ADD_INGREDIENT2,
(state, { ingredient }) => ({
...state,
ingredients: [...state.ingredients, ingredient],
})
)
);发布于 2022-11-19 09:56:05
问题是你使用的是不同类型的数据。
您的状态是一个数组,由[]表示;
课程的状态是一个对象,由{}表示;
{.}表示对象和..。是为了数组。这是问题的根本原因。
https://stackoverflow.com/questions/74494984
复制相似问题