gpt4 book ai didi

javascript - 如何在对象状态 react 中删除对象数组

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

我想从每个 storeData 对象内的每个 saveProduct 中删除项目

const initialState = {
storeData: [{
"code": "f1",
"name": "storage-no-1",
"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",
"saveProducts": [{
"code": "P1",
"id": "1",
"name": "product-no-1",
"size": 20,
},
{
"code": "P1",
"id": "2",
"name": "product-no-2",
"size": 20,
},
]
},
]
};

class App extends React.Component {
constructor(props) {
super(props);

this.state = initialState;
}

deleteItem(saveProductsId, storeCode) {
this.setState(prevState => {
prevState.storeData.map(store => {
if (store.code == storeCode) {
return {
...store,
saveProducts: [
...store.saveProducts.filter(product => product !== saveProductsId)
]
};
} else {
return store;
}
})
})
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

最佳答案

您需要在setState中返回新状态

deleteItem = (saveProductsId, storeCode) => {
this.setState(prevState => {
return {...prevState, storeData: prevState.storeData.map(store => {
if (store.code == storeCode) {
return {
...store,
saveProducts: [
...store.saveProducts.filter(product => product !== saveProductsId)
]
};
} else {
return store;
}
})
}
})
};

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

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