我在陣列的陣列中有一個專案,我想定位它并洗掉它。我的問題是如何訪問它并洗掉該特定專案而不對其進行變異。
代碼沙盒在這里
點擊這里
case appConstants.DELETE_IMAGE_SUCCESS:
return {
...state,
products: state.productImages.filter((item) => item !== action.payload)
};
uj5u.com熱心網友回復:
您應該傳遞一個額外的有效負載 - product。這樣我們就可以在state.products陣列中找到目標產品by productCode。假設ProductCode可以識別產品。
僅使用imageFileName無法確定它屬于哪個產品。
case appConstants.DELETE_IMAGE_SUCCESS:
console.log(state);
const nState = {
...state,
products: state.products.map((item) => {
if (item.productCode !== action.payload.product.productCode)
return item;
return {
...item,
productImages: item.productImages.filter(
(v) => v.imageFileName !== action.payload.imageFileName
)
};
})
};
console.log(nState);
return nState;
App.js:
// ...
const onDeleteImage = (imageFileName, product) => {
dispatch(deleteImage({ imageFileName, product }));
};
return (
<div className="App">
{(products || []).map((product, index) => (
<ProductCard
product={product}
key={index}
onDeleteImage={(imageFileName) =>
onDeleteImage(imageFileName, product)
}
/>
))}
</div>
);
// ...
代碼沙盒
uj5u.com熱心網友回復:
這是概念性解決方案:
case appConstants.DELETE_IMAGE_SUCCESS:
return {
...state,
products: state.products.map(product => ({
...product,
productImages: (product.productImages ?? [])
.filter(({imageFileName}) => imageFileName !== action.payload),
})),
};
警告:如果多個產品的影像與您要洗掉的影像具有相同的檔案名,則該影像也會從其他產品中洗掉。(這是當前有效負載中提供的資訊的限制。)如果該描述是您的程式的錯誤,那么您還需要在有效負載中提供產品 ID,以便僅過濾匹配產品的影像。
uj5u.com熱心網友回復:
您需要傳遞productIndex或id與imageFileName一起正確執行洗掉操作。否則,所有相同的產品imageFileName將被洗掉。
嘗試這個
case appConstants.DELETE_IMAGE_SUCCESS:
return {
...state,
products: (state.products || []).map((item, itemIndex) => {
if (itemIndex === action.payload.productIndex) {
return {
...item,
productImages: item.productImages.filter(
(image) => image.imageFileName !== action.payload.imageFileName
)
};
}
return item;
})
};
在 App.js 檔案中
const onDeleteImage = (productIndex, imageFileName) => {
dispatch(deleteImage(productIndex, imageFileName));
};
在操作 index.js 檔案中
export const deleteImage = (productIndex, imageFileName) => {
return {
type: appConstants.DELETE_IMAGE_SUCCESS,
payload: {
productIndex,
imageFileName
}
};
};
在 MediaCard.js 檔案中
<Button
type="button"
color="primary"
variant="contained"
onClick={() => onDeleteImage(productIndex, data.imageFileName)}
>
代碼沙箱 => https://codesandbox.io/s/redux- added-array-of-object-inside-another-aray-in-react-forked-xmghr ? file=/src/reducers/ productReducer.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366745.html
標籤:数组 反应 还原 ecmascript-6
上一篇:總和達到某個值的指標是什么
