[英]How to update array created with useState hook in react
I have an array created with useState hook我有一个用 useState 钩子创建的数组
const [items,setItems] = useState(['a','b','c'])
const [itemsUpdated, setItemsUpdated] = useState(0)
But updating this array with previous state corrupts itemsUpdated counter as map seems to run twice.但是用以前的 state 更新这个数组会损坏 itemsUpdated 计数器,因为 map 似乎运行了两次。
setItems(oldArray => {
console.log("I should be printed once but being printed twice")
return oldArray.map(item => {
setItemsUpdated(oldValue => oldValue + 1 )
return item
})}
)
console.log(itemsUpdated)
// expected itemsUpdated = 3
// but result is itemsUpdated = 6
While updating directly also corrupts updated value as setUpdated is async虽然直接更新也会破坏更新的值,因为 setUpdated 是异步的
setItems(Items.map(item => {
setItemsUpdated(itemsUpdated+1)
return item
}))
console.log(itemsUpdated)
// updated = 1
It is a working solution, but how it is working correctly is beyond me.这是一个可行的解决方案,但它如何正常工作超出了我的范围。 What is the correct way to update the previous state?
更新之前的 state 的正确方法是什么?
setItems(Items.map(item => {
setItemsUpdated(oldValue => oldValue + 1 )
return item
}))
console.log(itemsUpdated)
// updated = 3
EDIT: All the answers stating that map will run for each item of array are incorrect.编辑:所有说明 map 将为每个数组项运行的答案都是不正确的。
map
will run only once and return a same size array. map
将只运行一次并返回相同大小的数组。 It's the map's callback function that runs for each item of array.这是地图的回调 function 为数组的每个项目运行。
The problem is that map is like a foreach/for loop so it will run callbacks for all items.问题是 map 就像一个 foreach/for 循环,因此它将为所有项目运行回调。 The callback passed into the map will run two times as array has 2 items, so your value is updating twice.
传递给 map 的回调将运行两次,因为数组有 2 个项目,因此您的值会更新两次。
The map callback function will be called once for every oldArray item. map 回调 function 将为每个 oldArray 项目调用一次。
For example, if the oldArray is ['a', 'b']
, the setUpdated will be called once for each item in the array.例如,如果 oldArray 是
['a', 'b']
,则 setUpdated 将为数组中的每个项目调用一次。
A better approach would be to call setUpdated on an useEffect hook:更好的方法是在 useEffect 挂钩上调用 setUpdated:
useEffect(() => {
setUpdated(oldValue => oldValue + 1 )
}, [items])
This way, everytime items state changes, the setUpdate function will be called.这样,每次 state 项目发生变化时,都会调用 setUpdate function。 You can also map items inside the callback whenever you want.
您还可以随时在回调中使用 map 项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.