简体   繁体   中英

How can I remove a property from state object in React?

Here are properties of state object:

  const [items, setItems] = useState({
    key1: 'apple',
    key2: 'watermelon',
    key3: 'banana',
  });

I wonder, how I can delete specific property from this state object by handling delete?

 const handleDelete = (e) => { }

Thanks in advance

Here's one way: duplicate the object (so React notices the change), delete the key (maybe this is the JavaScript feature you were missing), and set the state.

const handleDelete = (e) => {
  const newItems = {...items};
  delete newItems.key2; // or whichever key you want
  setItems(newItems);
}

I'm curious whether there's an Object helper to do this all in one line.

@Wyck found a cleaner way, which uses the "rest" aspect of destructuring assignment :

const handleDelete = (e) => {
  const {key2, ...newItems} = items; // newItems gets all but key2
  setItems(newItems);
}

The best way is to use the callback function from setState And then return the new object.

setItems(prevState => {
    const {key2, ...newItems} = prevState;    
    return newItems;
});     

If you use this method, wrap your deleteElement in a useCallback hook and add items to the list of dependencies:

const deleteElement = useCallback((e) => { … }, [items]);

Combine this with the @edemaine solution ☺️

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