问题描述
我这里的产品可能有一个或多个图像。具体取决于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
);