gpt4 book ai didi

javascript - 如何删除 react 中对象状态中的项目数组

转载 作者:行者123 更新时间:2023-11-28 14:23:23 25 4
gpt4 key购买 nike

我想要删除对象状态下的每个项目数组

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;
}
})
})
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

最佳答案

浏览 storeDatafilter 中的每一项saveProducts 其中 id !== saveProductsId:

this.setState(prevState => {
const storeData = prevState.storeData.map(s =>
({ ...s, saveProducts: s.saveProducts.filter(p => p.id !== saveProductsId) }));
return { storeData };
})

关于javascript - 如何删除 react 中对象状态中的项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54494013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com