我希望删除对象状态下的每个项目Array
class App extends Component {
constructor(props) {
super(props);
this.state = {
storeData: [{
"code": "f1",
"name": "storage-no-1",
"capacity": 125,
"temperture": -18,
"humidity": 3,
"saveProducts": [{
"code": "P1",
"id": "1",
"name": "product-no-1",
"size": 20,
},
{
"code": "P1",
"id": "2",
"name": "product-no-2",
"size": 20,
},
]
},
{
"code": "f2",
"name": "storage-no-2",
"capacity": 15,
"temperture": -18,
"humidity": 25,
"saveProducts": [{
"code": "P1",
"id": "1",
"name": "product-no-1",
"size": 20,
},
{
"code": "P1",
"id": "2",
"name": "product-no-2",
"size": 20,
},
]
},
]
}
}
}
我的功能代码:
deleteItem = (saveProductsId,storeCode) => {
console.log("obj",saveProductsId)
console.log("ttt",storeCode);
this.setState(prevState => {
prevState.storeData.map(store => {
if (store.code == storeCode) {
return {
...store,
saveProducts: [
...store.saveProducts.filter(product => product !== saveProductsId)
]
};
} else {
return store;
}
})
})
};
///////////////////////////////////////////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ////////////////////
答案 0 :(得分:4)
浏览storeData
中saveProducts
和filter
中的每个项目,其中id !== saveProductsId
:
this.setState(prevState => {
const storeData = prevState.storeData.map(s =>
({ ...s, saveProducts: s.saveProducts.filter(p => p.id !== saveProductsId) }));
return { storeData };
})