gpt4 book ai didi

javascript - 从状态数组中删除项目并将该项目添加到另一个状态数组中

转载 作者:行者123 更新时间:2023-12-01 01:20:32 25 4
gpt4 key购买 nike

我想要从状态数组中删除项目并将此项目添加到另一个状态数组

deleteItem = (id) => {
this.setState(prevState => {
const index = this.state.productData.findIndex(item => item.id === id); this.state.storeData[0].saveProducts.push(this.state.productData.slice(index, 1))
return this.state.productData
})
}

Json StoreData ,将对象的产品项保存在数组中

[ 
{
"code": "f1",
"name": "storage-no-1",
"capacity": 125,
"temperture": -18,
"humidity": 3 ,
"saveProdoucts":[]
},
{
"code": "f2",
"name": "storage-no-2",
"capacity": 15,
"temperture": -18,
"humidity": 25,
"saveProdoucts":[]
},
{
"code": "R3",
"name": "storage-no-3",
"capacity": 40,
"temperture": 21,
"humidity": 30,
"saveProdoucts":[]
}
]

最佳答案

请检查下面的示例代码,单击每个项目时,它将从productData中删除该项目,并在storedData的saveProducts属性中添加相应的项目。

希望这能解决问题。请将代码保存在react本地开发中并尝试运行。

import React, { Component, Fragment } from 'react';

class App extends Component {

state = {
productData: [
{ id: 1, productName: "test 1" },
{ id: 2, productName: "test 2" },
{ id: 3, productName: "test 3" },
{ id: 4, productName: "test 4" }
],
storedData: [{ saveProducts: [] }]
}

addItem = (id) => {
const { productData } = this.state
this.setState(prevState => ({
productData: productData.filter(product => product.id !== id),
storedData: [
{
saveProducts: [
...prevState.storedData[0].saveProducts,
...productData.filter(product => product.id === id)
]
}
]
})
)
}

render() {
// Destructuring
const { productData, storedData } = this.state
return (
<Fragment>
<ul>
{productData.map(product => {
return (
<li
onClick={() => this.addItem(product.id)}
key={product.id}>
<p>{product.productName}</p>
</li>
)
})}
</ul>
<h2>
Saved Products
</h2>
{
storedData[0].saveProducts.length > 0 ?
storedData[0].saveProducts.map(product => {
return (
<p key={product.id}>
{product.productName}
</p>
)
})
:
"No Products Selected"
}
</Fragment>
);
}
}

export default App;

关于javascript - 从状态数组中删除项目并将该项目添加到另一个状态数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274276/

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