Redux点差运算符vs地图 [英] Redux Spread Operator vs Map

查看:46
本文介绍了Redux点差运算符vs地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Redux Reducer中的数组中有一个对象状态.

I have a State of objects in an Array (in my Redux Reducer).

const initialState = {
      items: [
        { id: 1, dish: "General Chicken", price: 12.1, quantity: 0 },
       { id: 2, dish: "Chicken & Broccoli", price: 10.76, quantity: 0 },
        { id: 3, dish: "Mandaran Combination", price: 15.25, quantity: 0 },
        { id: 4, dish: "Szechuan Chicken", price: 9.5, quantity: 0 }
      ],
      addedItems: [],
     total: 0
    };

我有一个动作将一个对象的数量加1,例如{id:1,菜:将军鸡,价格:10.76,数量:0}单击Cart.jsx中的按钮时.这是我尝试使用传播运算符的第一个Reducer:

I have an action to add 1 to the quantity of an object, such as {id:1, dish: Generals Chicken, price: 10.76, quantity:0} when a button in clicked in Cart.jsx. Here's the first Reducer I tried using the spread operator:

case "ADD_QUANTITY":
  let existing_item = state.addedItems.find(
    item => action.payload === item.id
  );

  return {
    ...state,
    addedItems: [
      ...state.addedItems,
      { ...existing_item, quantity: existing_item.quantity + 1 }
    ]
  };

这没有用,它没有向数量添加1,而是添加了另一个对象,该对象的数量设置为2.因此,我尝试使用这样的Map

This didn't work, instead of adding 1 to the quantity, it added another object with the quantity set to 2. . .So, I tried using Map like this

case "ADD_QUANTITY":
  return {
    ...state,
    addedItems: state.addedItems.map(item =>
      item.id === action.payload
        ? { ...item, quantity: item.quantity + 1 }
        : item
    )
  };

这正常工作.我的问题是,为什么散布算子不起作用?据我所知,它应该和地图做同样的事情?

And this worked correctly. My question is, why didn't the spread operator work? As far as I can tell, it should do the same thing as the Map?

推荐答案

在数组文字上下文中使用时,spread语法不重现键(索引),而仅重现值.与对象文字上下文中的散布语法相反,后者产生键/值对.后者允许先前的条目被具有相同密钥的新条目覆盖,但第一个不具有此行为:它始终散布所有值而无需考虑索引.

The spread syntax, when used in an array literal context, does not reproduce the keys (the indexes), but just the values. As opposed to the spread syntax in an object literal context, which produces key/value pairs. The latter allows previous entries to be overruled by a new entry, having the same key, but the first does not have this behaviour: it always spreads all values without regards for indexes.

在替换数组中的元素时,在复制它时,您需要:

When replacing an element in an array, while copying it, you need to:

  • 知道执行替换的索引,
  • 确保副本是Array的实例,而不仅仅是普通对象

您可以使用 findIndex Object.assign([],)满足这些需求:

You can use findIndex and Object.assign([], ) for addressing those needs:

case "ADD_QUANTITY":
  let index = state.addedItems.findIndex(
    item => action.payload === item.id
  );
  existing_item = state.addedItems[index];

  return {
    ...state,
    addedItems: Object.assign([], state.addedItems, {
      [index]: { ...existing_item, quantity: existing_item.quantity + 1 }
    })
  }

这篇关于Redux点差运算符vs地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆