我要从状态数组中删除项目,然后将此项目添加到另一个状态数组
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,对象在数组中的Saveproducts项
[
{
"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":[]
}
]
答案 0 :(得分:2)
请检查以下示例代码,单击每个项目,它将从productData中删除该项目,并将相应的项目添加到storedData的saveProducts属性中。
我希望这可以解决问题。请保存代码以响应本地开发并尝试运行它。
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;