在React中设置状态后访问更新的值
该组件呈现总和,该总和是由先前值计算的。
我知道批次是如何工作的以及为什么。我可以通过实现按钮并将按钮连接到单击事件处理程序来解决此问题,但是我想在计算()funciton中使用Onchange事件计算总和。
因此,我想在相同功能中处理设定状态和计算过程。
因此,我的Quiestion是如何获得NUM1和NUM2的更新值,NUM1和NUM2在同一批次中进行了更新:
setSum(parseFloat(**Updated**num1) + parseFloat(**Updated**num2))
-
export default function Home() {
const [num1 , SetNum1] = useState(0.0)
const [num2 , setNum2] = useState(0.0)
const [sum, setSum] = useState(0.0)
const calculate = (e) => {
switch(e.target.id){
case 'num1':
SetNum1((prev) => {
return e.target.value
})
break;
case 'num2':
setNum2((prev) => {
return e.target.value
})
break;
}
setSum(parseFloat(num1) + parseFloat(num2))
}
return (
<div>
<form>
<input type="number" className="form-control" id="num1" value={num1} onChange={(e) => calculate(e)} />
<input type="number" className="form-control" id="num2" value={num2} onChange={(e) => calculate(e)} />
Sum : {sum}
</form>
</div>
)
}
可以在SETNUM1之后访问最新的NUM1值,还是我必须实现一个计算总和的按钮?
The component renders the sum , which was calculated by previous values.
I know how batches work and why is this. I could solve this by implementing a button and connect the button to a click event handler , but I would like to calculate the sum with onChange Event inside the calculate() funciton .
So I would like to handle the set state and the calculation process in the same function.
So my quiestion is how could I get the updated value of num1 and num2 , which was updated in the same batch:
setSum(parseFloat(**Updated**num1) + parseFloat(**Updated**num2))
--
export default function Home() {
const [num1 , SetNum1] = useState(0.0)
const [num2 , setNum2] = useState(0.0)
const [sum, setSum] = useState(0.0)
const calculate = (e) => {
switch(e.target.id){
case 'num1':
SetNum1((prev) => {
return e.target.value
})
break;
case 'num2':
setNum2((prev) => {
return e.target.value
})
break;
}
setSum(parseFloat(num1) + parseFloat(num2))
}
return (
<div>
<form>
<input type="number" className="form-control" id="num1" value={num1} onChange={(e) => calculate(e)} />
<input type="number" className="form-control" id="num2" value={num2} onChange={(e) => calculate(e)} />
Sum : {sum}
</form>
</div>
)
}
Is it possible to access the most recent num1 value after SetNum1 or I have to implement a button which calculates the sum?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想收听
使用效果
的更改。You want to listen for changes with
useEffect
.您不需要将总和保持状态。由于它是从其他两个状态变量得出的,因此您可以并且应该在每个渲染上进行计算:
这是最简单,最有效的解决方案。也不需要使用。
这是更多的解释和一个可运行的示例: https:// react .dev/learn/choosing-the-state-structure#avoid-redundant-state
You don't need to keep the sum in state. Because it is derived from the two other state variables, you can and should just calculate it on each render:
This is the simplest and most efficient solution. No useEffect() needed either.
Here is more explanation and a runnable example: https://react.dev/learn/choosing-the-state-structure#avoid-redundant-state