首页 > 解决方案 > 在 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)
}

标签: javascriptreactjsreact-hooks

解决方案


设置状态本质上是异步的,所以 -

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)
}

推荐阅读