Redux在Reaction中添加了另一個Aray內的對象數組 [英] Redux Added Array of Object Inside Another Aray in React
本文介紹了Redux在Reaction中添加了另一個Aray內的對象數組的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我這里的產品可能有一個或多個圖像。具體取決于ProductCode。 如果ProductCode為,則它們屬于同一產品??梢栽趫D像的文件名上找到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屋!
查看全文