简体   繁体   English

如何使用反应钩子更新对象?

[英]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.我想在用户单击按钮时更新我的​​对象,附加到数组元素 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.我通过了 prevState 回调,但它不起作用。

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.当您执行destinations:[ e.currentTarget.id] ,您实际上是在覆盖现有数组。

You need to do this,你需要这样做,

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

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM