简体   繁体   中英

Delete items from state array and add this items another state array

I'm want Delete items from state array and add this items another state array

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 item of object in array

[ 
  { 
  "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":[]
  } 
 ]

please check the below sample code, on click of each item it will remove the item from the productData and add the corresponding item in the saveProducts property of the storedData.

I hope this will solve the issue. Please save the code in react local development and try to run it.

 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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM