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)
];
我的 NgRx 操作:
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] })
)
);
我正在學習有關 Angular 的課程。我想用新版本、新語法來處理那個課程中使用 switch/case 對舊版本所做的事情。
我有一個陣列,我想使用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;
}
}
uj5u.com熱心網友回復:
在您的NgRx Reducer中,您應該使用解構賦值來解壓ingredient屬性并將其添加到ingredients陣列中:
ingredients: [...state.ingredients, ingredient]
減速器代碼:
export const shoppingListReducer = createReducer(
initialState2,
on(ShoppingListActions.ADD_INGREDIENT2,
(state, { ingredient }) => ({
...state,
ingredients: [...state.ingredients, ingredient],
})
)
);
uj5u.com熱心網友回復:
問題是您使用的是不同型別的資料。
你的狀態是一個陣列,用[]表示;
課程的狀態是一個物件,用{}表示;
{...} 用于物件,[...] 用于陣列。這就是問題的根本原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/537246.html
