简体   繁体   中英

React remove one item of grouped array useState

hey how can i remove an object from an grouped array ? my grouped array looks like the picture , its grouped by the date and i want to remove one item from it in my function:

  const [inCard, setInCard] = useState(0);
  const [events, setEvents] = useState([]);
  const [eventsInCard, setEventsInCard] = useState([]);

  function addToCard(event) {
    if (!eventsInCard.some((e) => e._id === event._id)) {
      setEventsInCard([...eventsInCard, event]);
      newValueInCard++;
      setEvents((events) => 
            events.filter((item) => 
                item._id === event._id)); //<= not working because its an object 
    }
    setInCard(newValueInCard);
  }

can someone help me ? its not working分组数组

You can create helper to remove key and use it on previous state, like this:

const removeKey = (key, { [key]: _, ...rest }) => rest;
...
...
setEvents(prev => removeKey(event._id, prev)); // If event._id is datetime-like key you want to delete, otherwise replace it with appropriate one

UPDATED

If you want to update array inside object(under some date-like key), then you can do in this way:

const dateKey = event.somePropFromEvent; // YOU NEED TO KNOW UNDER WHICH KEY IS ARRAY YOU WANT TO MODIFY
const id = event._id;

setEvents(prev => ({...prev, [dateKey]: prev[dateKey].filter(x => x._id !== id)}));

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