在 React js useState() 钩子中更改多个状态 [英] changing multiple states in react js useState() hook
问题描述
所以我想知道当我在处理程序函数中更改多个状态时实际会发生什么.它们是同时更新还是一个接一个执行.
So I was wondering what actually happens when I change more than one state in a handler function. Will they both get updated simultaneously or they will be executed one after another.
const [x, setX] = useState(0)
const [y, setY] = useState(0)
const handlerFunction = () => {
setX(x+1)
setY(y+1)
}
如果一个国家依赖其他国家又会怎样?
Also what If one state depend on others?
const handlerFunction = () => {
setX(x+1)
setY(x+1)
}
或者如果
const [x, setX] = useState(0)
const [y, setY] = useState(x)
const handlerFunction = () => {
setX(x+1)
setY(y+1)
}
推荐答案
JavaScript* 中没有任何东西同时运行,因此状态更新一个接一个地进行.但由于它们都是异步完成的,因此在下一次渲染之前您不会看到 x
或 y
更新,因此从您的角度来看它们会同时出现.
Nothing ever runs simultaneously in JavaScript*, so the state updates occur one after the other. But since they're both done asynchronously, you won't see x
or y
update until the next render, so it will appear simultaneous from your perspective.
因此在上述所有三种情况下,在调用 handlerFunction()
一次后,x
和 y
的最终值将是 1 和 1.
So in all three cases above, the final values for x
and y
after calling handlerFunction()
once will be 1 and 1.
还要注意,因为 x
和 y
只是变量,它们的值不能无论如何同步变化,这就是为什么你只看到它们的值在下一次渲染中更新.
Also note that because x
and y
are simply variables, their values can't change synchronously anyway, which is why you only see their values update in the next render.
不过请注意,使用功能更新是一种很好的做法 当你的状态改变依赖于之前的状态时:
Just so you're aware though, it's good practice to use functional updates when your state changes rely on the previous state:
const handlerFunction = () => {
setX(x => x + 1)
setY(y => y + 1)
}
这可确保每次更新都是原子操作.
This ensures that each update is an atomic operation.
*除非你正在处理工作线程
这篇关于在 React js useState() 钩子中更改多个状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!