简体   繁体   中英

How to conditionally remove a value from a javascript object during a setState call in ReactJS?

updateDishDetails(id, quantity) {

    if (quantity !== 0) {
      this.setState(
        prevState => ({
          bookingFormData: {
            ...prevState.bookingFormData,
            dishDetails: {
              ...prevState.bookingFormData.dishDetails,      // WORKING
              [id]: quantity,                                // PERFECTLY
            },
          },
        })
      );
    }

   if (quantity === 0) {
      this.setState(
        prevState => ({
          bookingFormData: {
            ...prevState.bookingFormData,
            dishDetails: {
             // ...prevState.bookingFormData.dishDetails,   // NEED HELP HERE
            // [id]: quantity,                             // AND HERE
            },
          },
        })
      );
    }

  }

I have the above function where I set the state of dishDetails based on the value of quantity.

What do I want to achieve?

  1. When the quantity !== 0 set the state of dishDetails as shown. ( This is working Perfectly )
  2. When the quantity === 0, I want to remove that particular id from the dishDetails , but the previous state should be maintained. ( I need help in solving this )

The relevant state is a follows:

this.state = {
   bookingFormData: {
      dishDetails: []
   }
}

You can use destructuring assignment and the rest operator to create a new object and remove a prop :

if (quantity === 0) {
      this.setState(
        prevState => {
          const { [id]: removedId, ...newDishDetails } = prevState.bookingFormData.dishDetails;
          return {
            bookingFormData: {
              ...prevState.bookingFormData,
              dishDetails: newDishDetails,
            },
          },
        }
      );
    }

Can you nullify the id?

Set the id's value to null to remove the content.

dishDetails: {
  ...prevState.bookingFormData.dishDetails,
  [id]: null,
},

if its an array thats easier

dishDetails: {
  ...prevState.bookingFormData.dishDetails.filter((item) => item.id !== id),
},

or if input and output are both objects

dishDetails: {
  ...Object.entries(prevState.bookingFormData.dishDetails)
    .filter(([key, item]) => item.id !== id)
    .reduce((acc, [key, item]) => ({...acc, [key]: item}), {}),
},

I'll use the delete operator :

if (quantity === 0) {
 const dishDetails = {...this.state.bookingFormData.dishDetails}
 delete dishDetails[id];

this.setState(
  prevState => ({
    bookingFormData: {
      ...prevState.bookingFormData,
      dishDetails
   }
  })
 )
}

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