javascript 如何在react redux中更新一个特定的项目?

omjgkv6w  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(228)

react redux的初始状态。
reducer.js

cart {
  id: 100,
  name: "Pizza",
  price: 550,
  category: "Fasting",
  time: "20-50 min",
  restaurantId: "BH001",
  quantity: 1,
  photo: {
    fileName: "",
    fileType: "",
    filePath: "",
  },
  description:"The food is ...",
},

更新数量要素时所做的操作。

case "INCREASE_DECREASE_ORDER_AMOUNT":
  return {
    ...state,
    carts: [
      ...state.cart.map((val) => {
        if (val.id === action.payload) {
          if (action.typo == "+") {
            return {
              ...val,
              quantity: val.quantity + 1,
            };
          }
        }
      }),
    ],
  };

react redux的作用。
action.js

const increaseDeacreaseOrderAmount = (id, typo) => {
  return {
    type: "INCREASE_DECREASE_ORDER_AMOUNT",
    payload: id,
    typo: typo,
  };
};

export { increaseDeacreaseOrderAmount }

index.js

onPress={() => {
  dispatch(increaseDeacreaseOrderAmount(value.id, "+"));
}}

问题是reducer中的quantity没有更新。

xzlaal3s

xzlaal3s1#

INCREASE_DECREASE_ORDER_AMOUNT reducer的情况看起来 * 大部分 * 正确,因为它正确地浅复制了它正在更新的状态。我看到的问题是,它不返回定义的state.cart项目的项目,它***不是***更新。Array.prototype.map应该为它所操作的数组的每个元素返回一个值。

case "INCREASE_DECREASE_ORDER_AMOUNT":
  return {
    ...state,
    carts: [
      ...state.cart.map((item) => {
        if (item.id === action.payload) {
          if (action.typo == "+") {
            return {
              ...item,
              quantity: item.quantity + 1,
            };
          }
        }

        // return un-updated cart item
        return item;
      }),
    ],
  };

相关问题