当前位置: 首页 > 知识库问答 >
问题:

有人能在下面的例子中解释一下...扩展运算符的用法吗?[副本]

糜昌胤
2023-03-14

根据我的理解,这是spread operator的工作方式:

x=[1,2,3];

y=[...x,4,5]; 

//这与y=[1,2,3,4,5]相同

const initialState={
  ingredients: [
    new Ingredient('Apples', 5),
    new Ingredient('Tomatoes', 10),
  ]
};
export function shoppingListReducer( state=initialState, action:ShoppingListActions.ShoppingListActions ) {
  switch(action.type) {
    case ShoppingListActions.ADD_INGREDIENT:
      return {
        ...state,
        ingredients:[...state.ingredients,action.payload ]
      }

    default:
      return state;
  }
return {
  ...state,
  ingredients:[...state.ingredients,action.payload ]
}

有效载荷属于以下类型:

export class Ingredient {
  constructor(public name: string, public amount: number) {}
}

共有1个答案

鲜于高明
2023-03-14

基本上,您试图创建一个具有stateobject的所有属性的对象,并用值重写其属性appitions,作为state.appitions数组和action.payload中的所有值。这可能是为了将result对象的引用与state对象分离。

var state = {
  "someprop" : "somevalue",
  "ingredients" : ["a", "b"]
};

var action = {
  "payload" : 4
};

var result = {
  ...state,
  ingredients:[...state.ingredients,action.payload ]
};
state.someprop = "somevalue1"; // does not alter result object
state.ingredients.push("c"); // does not alter result object
console.log(result);
 类似资料: