简体   繁体   中英

How to update object using react hooks?

I want to update my object when the user clicks on the button, append to array element id. But when I adding data to array it overrides all object without saving previous data. I passed prevState callback but it doesn't work.

const [filteredObject, setFilter] = useState({destinations:[],season:[],difficulty:[],price:'',is_exclusive:'',duration:''});

if (e.currentTarget.name==='destinations') {
   setFilter(prevState=>({...prevState, destinations:[ ...prevState.destinations, e.currentTarget.id]}))
}

在此处输入图片说明

When you do destinations:[ e.currentTarget.id] , you are actually overriding the existing array.

You need to do this,

setFilter( prevState => ({
   ...prevState, 
   destinations:[ ...prevState.destinations, e.currentTarget.id ]
}))

Demo

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