[英]Set State of a list
When I tried to set the state of my list, I tried two methods.当我尝试设置列表的 state 时,我尝试了两种方法。
setEatenFoodList(prevList => {
prevList.unshift(addedFood);
return prevList;
})
This method adds the addedFood two times.此方法将 addedFood 添加两次。
setEatenFoodList([...eatenFoodList, addedFood])
When this method adds it one time, which is what I want.当此方法添加一次时,这就是我想要的。 But, I want to know the difference between these two methods.但是,我想知道这两种方法之间的区别。
As to your last question what both methods are doing are similar with unshift
adding the addedFood
in front of the eatenFoodList
array while the in second method eatenFoodList
is first destructured and then addedFood
is added.至于你的最后一个问题,这两种方法的作用与unshift
在eatenFoodList
数组前面添加addedFood
相似,而第二个方法eatenFoodList
首先被解构,然后添加addedFood
。
Need more context on what conditions you are updating the eatenFoodList
state to find out how the first method is executing twice.需要更多关于更新eatenFoodList
state 的条件的上下文,以了解第一个方法是如何执行两次的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.