首页 > 解决方案 > useState 变量未在代码片段的第一次运行时设置

问题描述

我正在 React 中制作 Windows 10 计算器克隆,我被困在下面的这段代码中:

function Calculator(){ //for providing context of the situation

    const [currentValue, setCurrentValue] = useState('0')
    const [aMath, setAMath] = useState('')
    const [bMath, setBMath] = useState('')
    const [calcShow, setCalcShow] = useState('')
    const [symbolMath, setSymbolMath] = useState('')
    const [newValue, setNewValue] = useState(true)

    const handleClick = (e) => {
    ...
        else if(symbol === '+'){
            if(aMath === '')
                 setAMath(currentValue)
            else
                 setBMath(currentValue)
            setCalcShow(aMath+symbol+bMath)
            setNewValue(true)
            console.log({a: aMath,b: bMath,currentValue})
            setSymbolMath(symbol)
        }
...
    }
}

问题是,在第三次或第二次按下“+”按钮时,setAMath 和 setBMath 已完全执行,其他一切都运行良好。我想立即更改 bMath 变量。console.log() 显示, currentValue 更新正常,但其余的初始状态为 '' 并且在前面提到的情况下发生了变化。我需要做什么?

标签: javascriptreactjsreact-hooks

解决方案


这是因为Reactjs 的更新批处理机制


当在 onChange、onClick 等事件处理程序中更新状态时,React 会将所有内容批处理setState为一个:

将您的日志放在return函数之前以查看最新值。

或者在一个useEffect

useEffect(() => {
  console.log("aMath", aMath);
},[aMath]);

但是这种行为将在 Reactjs 18 中改变,如此处所述


推荐阅读