为什么普通计数器只运行最后一个 setCount 参数,而功能计数器运行所有 setCount?
为什么第一个只运行最后一个 setCount 参数,而当我们使用 setCount 的箭头函数时,它会运行两个参数。
例如:如果您单击“正常”按钮,计数将为5,因为它应该为9
如果您单击“功能”按钮,计数将为2,因为它同时运行 SetCount
import react, { useState, useEffect } from "react";
export default function App() {
const [count, setCount] = useState(0);
console.log(count);
return (
<div className="App">
<button
onClick={() => {
setCount(count + 1);
setCount(count + 3);
setCount(count + 5);
}}
>
Normal
</button>
<br />
<button
onClick={() => {
setCount((c) => c + 1);
setCount((c) => c + 1);
}}
>
Functional
</button>
</div>
);
}
Why the first one is only running the last setCount argument and when we are using the arrow function for setCount it's running both the argument.
eg: if you click the Normal button the count will be 5 as it should be 9
If you click the Functional button the count will be 2 as it is running both the SetCount
import react, { useState, useEffect } from "react";
export default function App() {
const [count, setCount] = useState(0);
console.log(count);
return (
<div className="App">
<button
onClick={() => {
setCount(count + 1);
setCount(count + 3);
setCount(count + 5);
}}
>
Normal
</button>
<br />
<button
onClick={() => {
setCount((c) => c + 1);
setCount((c) => c + 1);
}}
>
Functional
</button>
</div>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我们使用一次参数设置值
在计数上设置当前值并运行 3 个带参数的方法
但在这种情况下:
setCount((c) => c + 1);
当(c)=>时c+1调用c的方法每次获取当前值
when we use parameter set value once
current value set on the count and run 3 methods with parameters
but in this case :
setCount((c) => c + 1);
when (c) => c + 1 method called c get the current value each time
您的“正常”代码捕获闭包中 count 的当前状态值。第一次渲染组件时,这基本上归结为以下内容:
由于状态更新是批量更新的,所以最后一个获胜,因此结果状态值为 5。
“功能”代码示例使用回调
Dispatch
,它为您提供更改发生时状态的先前值,不受关闭的影响。基本上:两者都有其用途,取决于您想要什么。
Your "normal" code captures the current state value of count in a closure. The first time your component is rendered this basically boils donw to following:
As state updates are batched the last one wins, so the resulting state value is 5.
The "Functional" code sample uses the callback
Dispatch
, that provides you with the previous value of state at the time your change happens, not affected by closures. Basically:Both have their uses, depends on what you want.
在计算值的总和时,在您的情况下,从 1、3 和 5 的总和计算 9,我们需要将一个函数传递给
setCount
,参数为先前的值这在官方文档中有记录:
https://reactjs.org/docs/hooks-reference.html#function-updates
When computing the sum of values, in your case, calculating 9 from the sum of 1, 3 and 5, we need pass a function to
setCount
with the parameter being the previous valueThis is documented in official doccs:
https://reactjs.org/docs/hooks-reference.html#functional-updates