【问题标题】:Can someone explain the use of ...spread operator in the following example? [duplicate]有人可以在下面的示例中解释 ...spread 运算符的使用吗? [复制]
【发布时间】:2019-10-10 08:08:47
【问题描述】:

据我了解,这是传播运算符的工作原理:

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) {}
}

【问题讨论】:

  • 你也可以传播对象:{ ...state}这里state是一个对象。通过使用{},结果将是一个对象。
  • 你的有效载荷类型是什么?
  • @RezaRahmati 有效载荷:成分export class Ingredient { constructor(public name: string, public amount: number) {} }
  • IngredientsIngredient 不同。 Ingredients是什么类型的?

标签: javascript angular typescript ecmascript-6 redux


【解决方案1】:

基本上,您正在尝试使用state 对象的所有属性创建一个对象,并使用state.ingredients 数组中的所有值以及action.payload 覆盖其属性ingredients。这可能是为了将结果对象的引用与状态对象分开

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);

或者,为了更好地理解它,您可以将其分解为以下内容

var result = {...state};
result.ingredients = [...state.ingredients, action.payload];

注意:如果state中存在嵌套对象或array中存在对象,它们仍将继续共享相同的引用。

【讨论】:

    【解决方案2】:

    在对象内部使用时,将其视为 object.assign。原始状态被添加到对象,然后是下一件事(成分),如果需要,覆盖已经存在的任何内容(成分),依此类推

    【讨论】:

    • 为什么投反对票?这有助于他以一种简单的方式概念化和理解正在发生的事情,而无需使用过于技术性的答案。
    猜你喜欢
    • 2011-04-05
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2011-08-18
    • 2018-07-28
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多