javascript - 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 更新正常,但其余的初始状态为 '' 并且在前面提到的情况下发生了变化。我需要做什么?
解决方案
这是因为Reactjs 的更新批处理机制
当在 onChange、onClick 等事件处理程序中更新状态时,React 会将所有内容批处理setState
为一个:
将您的日志放在return
函数之前以查看最新值。
或者在一个useEffect
:
useEffect(() => {
console.log("aMath", aMath);
},[aMath]);
但是这种行为将在 Reactjs 18 中改变,如此处所述
推荐阅读
- c++11 - reference to 'rank' is ambiguous
- matlab - 使用“subs”函数评估“dsolve”的输出在 Maltab 中提供额外的输出
- angular - 用于垫表的单个列过滤器
- ionic3 - 错误:未捕获(承诺中):错误:StaticInjectorError(AppModule)[login]:Ngx-translate
- c++ - C++ 包含文件错误
- javascript - Curiosity on react(?) or javascript syntax
- batch-file - 从文件循环读取的行在批处理程序中未正确分配
- reactjs - Cannot read property 'Vector'/'Draw' of undefined in React JS
- python - 使异步事件循环响应 Windows(和 Unix)上的 KeyboardInterrupt
- c# - AForge 在加载大尺寸 AVI 文件时显示错误:“无法打开指定的 AVI 文件”