谁能给我解释一下这个代码吗?我无法理解这里发生了什么.

const cartReducer = (state, action) => {
  if (action.type === "ADD") {
    const updatedTotalAmount =
      state.totalAmount + action.item.price * action.item.amount;

    const existingCartItemIndex = state.items.findIndex(
      (item) => item.id === action.item.id
    );

    const existingCartItem = state.items[existingCartItemIndex];
    let updatedItems;

    if (existingCartItem) {
      const updatedItem = {
        ...existingCartItem,
        amount: existingCartItem.amount + action.item.amount,
      };
      updatedItems = [...state.items];
      updatedItems[existingCartItemIndex] = updatedItem;
    } else {
      updatedItems = state.items.concat(action.item);
    }

    return {
      items: updatedItems,
      totalAmount: updatedTotalAmount,
    };
  }
  return defaultCartState;
};

推荐答案

我已经在你的代码中添加了一些注释,希望这能让代码更容易理解.

const cartReducer = (state, action) => {
  // Adding an Item to Cart
  if (action.type === "ADD") {
    // Calculated Cart Total: existing Total + (new Item Price * new item Quantity)
    const updatedTotalAmount = state.totalAmount + action.item.price * action.item.amount;

    /* 
     * Finding Items Index in the Cart Array using the Item ID.
     * Index will be Returned only if Item with same od already exist otherwise -1
     */
    const existingCartItemIndex = state.items.findIndex((item) => item.id === action.item.id);
    /*
     * Getting the CartItem Based on the Index.
     * If the value is -1 i.e., item already doesn't exist, then this code will return undefined
     */
    const existingCartItem = state.items[existingCartItemIndex];

    let updatedItems;
    // existingCartItem will have an Object(which evaluates to true) only if Item already existed in Cart
    if (existingCartItem) {
      // Creating updatedItem by spreading the existingItems data + updating amount/Quantity to: existing Quantity + new Quantity
      const updatedItem = {
        ...existingCartItem,
        amount: existingCartItem.amount + action.item.amount,
      };

      // Making a Copy of Items Array & Replacing Existing Item with new/updated entry
      updatedItems = [...state.items];
      updatedItems[existingCartItemIndex] = updatedItem;
    } else {
      // If the Item doesn't already exist in Cart then we Just add that New Item to the Cart
      updatedItems = state.items.concat(action.item);
    }

    // Return the State with Updated Items List & total Amount
    return {
      items: updatedItems,
      totalAmount: updatedTotalAmount,
    };
  }

  // Default State Return
  return defaultCartState;
};

Reactjs相关问答推荐

迁移到React Router Dom v6后,我是否错误地使用了Link组件?

react 派生状态未正确更新

是否将样式应用于父悬停(框架运动)上的子元素?

在Reaction中测试条件组件

包装组件可以避免子组件重新渲染.?

TypeError:b不是React.js中的函数错误

我应该如何管理设置组件初始状态的复杂逻辑?

MUI:在props 主题中找到的值:;错误;是[Object],而不是字符串或数字

如何清除过滤器搜索的状态

React router v5 仅在生产中不适用于嵌套路由

Next.js 和理智 | npm run build 时预渲染页面/时发生错误

如何在 JS 中绘制具有不同笔画宽度的样条线

React - 使用 React 显示错误和积极alert

如何在不重新加载页面的情况下加载新添加的数据?

React JS:如何判断用户使用的是浏览器 url 还是桌面 electron

React Native PermissionsAndroid 不包括 READ_MEDIA_IMAGES.如何解决这个问题?

模块解析失败:意外令牌 (257:106) 您可能需要适当的加载程序来处理此文件类型

CORS 政策:无访问控制允许来源-AWS 和 Vercel

useEffect 仅在跟随链接后有效,不适用于直接链接

React Router Dom V6 中的嵌套路由