【问题标题】:How to change value of object which is inside an array using react redux?如何使用 react redux 更改数组内对象的值?
【发布时间】:2021-02-17 16:15:38
【问题描述】:

我正在尝试实现一个名为“addToCart”的函数,该函数负责在用户单击特定产品时将产品添加到“cartItems”状态中。我可以添加任意数量的产品。 但是每当我点击一个特定的产品时,如果它已经在我的购物车中,我想更改它的数量,而不是添加重复的项目。无论我点击特定产品多少次,我都想增加项目数量。 我已经上传了一些代码以使其更简洁。

初始状态

  const initState = {
    cartItems: []
    }

购物车减速器

case CART_ADD_ITEM:
  const item = action.payload;
  const existItem = state.cartItems.find((x) => x.product === item.product);
  if (existItem) {
    return {
      ...state,
      cartItems: state.cartItems.map((x) =>
        x.product === existItem.product ? { ...item, qty: item.qty + 1 } : x
      ),
    };
  } else {
    return {
      cartItems: [...state.cartItems, item],
    };
  }

cartActions

export const addToCart = (productId, qty) => async (dispatch, getState) => {
  try {
    const { data } = await Axios.get(`/api/products/${productId}`);
    dispatch({
      type: CART_ADD_ITEM,
      payload: {
        name: data.name,
        price: data.price,
        product: data._id,
        qty,
      },
    });
  } catch (error) {
    console.log(error.response);
  }
};

产品组件

import React from "react";
import { useDispatch } from "react-redux";
import { addToCart } from "../actions/cartActions";
const Product = ({ product, qty }) => {
  const dispatch = useDispatch();
  const addToCartHandler = () => {
    dispatch(addToCart(product._id, qty));
  };
  return (
    <div className="product-card" onClick={addToCartHandler}>
      <h3>{product.name}</h3>
      <p>{product.price}</p>
    </div>
  );
};

export default Product;

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    仔细查看了代码。实施似乎是有道理的。我刚刚在cardReducers.js中添加了两件事

    1. 使用() 包装返回对象。如果您正在使用? : 运算符和map 的简写语法,则不确定编译器是否可以正常工作以知道您要返回一个对象
    2. 对于 else 案例,添加 ...state 以防您将来有更多属性。
    case CART_ADD_ITEM:
      if (existItem) {
        const isCurrentlyExist =  x.product === existItem.product 
    
        return {
          ...state,
          cartItems: state.cartItems.map(x => (isCurrentlyExist ? { ...item, qty: item.qty + 1 } : x)
        };
      } else {
        return {
          ...state,   //if you have other state in the future
          cartItems: [...state.cartItems, item],
        };
      }
    

    【讨论】:

    • 我尝试了您的解决方案,但 vs 代码会自动删除这些括号并再次出现相同的情况。
    • 检查我更新的答案。如果这也被 vscode 插件删除。直接新建一个对象,将qty加1。然后在map中返回,看看是不是真的有问题。
    • 现在我可以增加数量,但只能增加一次。我不能从 2 增加数量。
    • 你的代码现在写得怎么样了?你的意思是每次增加2?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多