javascript - 在 react js useState() 钩子中更改多个状态
问题描述
所以我想知道当我在处理函数中更改多个状态时实际会发生什么。它们会同时更新还是会一个接一个地执行。
const [x, setX] = useState(0)
const [y, setY] = useState(0)
const handlerFunction = () => {
setX(x+1)
setY(y+1)
}
如果一个状态依赖于其他状态怎么办?
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)
}
解决方案
设置状态本质上是异步的,所以 -
const handlerFunction = () => {
setX(x+1)
setY(x+1) // here the old value of x will be taken and the outcome value of x and y will be different //
}
这里 -
const [x, setX] = useState(0)
const [y, setY] = useState(x) // this is just to initialize an initial value to your state y so it will be once set to the value of x and then it doesn't depends on x//
const handlerFunction = () => {
setX(x+1)
setY(y+1)
}
推荐阅读
- java - 当我只使用两个十进制数时,为什么在相加时会得到大的十进制数,如何在 Java 中修复它?
- powershell - Powershell中有没有办法将变量的值附加或预先添加到管道命令的输出中
- bash - 使用大小写组织 Bash 菜单
- c - 如何在C中找到哪个函数正在调用另一个函数?
- docker - Why does Docker require PATH when building from custom Dockerfile in another directory?
- java - 这是由方法 System.gc() 引起的 CMS gc 吗?
- java - 为什么我在向 Spring 3 控制器发出 POST 请求时收到 SRVE0295E?
- java - MapStruct : Mapping Collections objects based on it's type's properties
- excel - 处理 Excel 文档中的无效 XML 属性
- kubernetes - Is it possible to Reverse-dns query for a POD IP address to get its hostname for a Kubernetes Deployment?