简体   繁体   中英

How To delete items Array in objects state in react

i'm want the each items Array in objects state delete

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,
            },
          ]
        },
      ]
    }
  }
}

my function code :

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

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

Go through each item in storeData and filter the saveProducts where the id !== saveProductsId :

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

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