Redux在Reaction中添加了另一个Aray内的对象数组 [英] Redux Added Array of Object Inside Another Aray in React

查看:0
本文介绍了Redux在Reaction中添加了另一个Aray内的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里的产品可能有一个或多个图像。具体取决于ProductCode。 如果ProductCode为,则它们属于同一产品。可以在图像的文件名上找到ProductCode,它在第一个下划线之后。例如,如果文件名为AA_BB_CC.jpg。ProductCode为bb。

您可以查看"我的代码"框中的样本图像。

因此,如果图像具有相同的ProductCode,它应该加起来就是产品。我的问题是在这一部分。正在添加具有相同ductCode的产品图像。

这是代码沙箱 CLICK HERE

代码

  return {
    ...state,
    products: [...state.products, ...action.payload]
  };

预期产量

预期产量的响应

推荐答案

我看到您在创建文件图像对象时已经在文件上传器中进行了字符串拆分。在本例中,您只需要检查生成的productCode图像对象有效负载,看看它是否已经包含在products数组中。如果不是,则生成新的产品状态对象并将图像添加到数组中,否则将不变的更新模式应用于浅层复制状态并追加新的文件对象。

由于操作负载中的每个产品可能属于不同的产品,您需要迭代此数组以确定每个新产品应该合并到哪里。

case appConstants.UPLOAD_PRODUCT_SUCCESS:
  // (1) iterate the product images array
  return action.payload.reduce(
    (
      state,
      {
        productCode,
        productName,
        productCategory,
        imageFile,
        imageFileName
      }
    ) => {
      // (2) Check if the product is already in state
      const shouldUpdate = state.products.some(
        (product) => product.productCode === productCode
      );

      // (3a) If we just need to return updated state with added new image
      if (shouldUpdate) {
        return {
          ...state,
          // (4) shallow copy the products array
          products: state.products.map((product) =>
            product.productCode === productCode
              // (4b) If this is the matching product, shallow copy product
              // append a new image file object with new id
              ? {
                  ...product,
                  productImages: product.productImages.concat({
                    id: uuidV4(),
                    imageFile,
                    imageFileName
                  })
                }
              // (4b) copy forward existing product object
              : product
          )
        };
      }

      // (3b) Create a new product object and initially populate images array
      return {
        ...state,
        products: state.products.concat({
          productCode,
          productName,
          productCategory,
          productExisting: true,
          productImages: [
            {
              id: uuidV4(),
              imageFile,
              imageFileName
            }
          ]
        })
      };
    },
    state
  );

这篇关于Redux在Reaction中添加了另一个Aray内的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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