reactjs - 使用 useState 钩子时计数器不增加
问题描述
我有以下代码:
const [count1, setCount1] = useState(0);
const handleAsyncUpdate = async () => {
setCount1(count1 + 2);
setCount1(count1 + 1);
};
const handleSyncUpdate = () => {
setCount1(count1 + 2);
setCount1(count1 + 1);
};
console.log("render", count1);
return (
<div className="App">
<h2>{count1}</h2>
<button type="button" onClick={handleAsyncUpdate}>
Click for async update
</button>
<button type="button" onClick={handleSyncUpdate}>
Click for sync update
</button>
</div>
);
}
当我单击第二个按钮时,我希望<h2>{count1}</h2>
渲染3
(0 + 1 + 2),但它会渲染1
.
如果我切换setCount1(count1 + 1);
到setCount1(count => count + 1);
那么它可以正常工作,但是为什么呢?
解决方案
我认为您对工作方式useState
(或者即使this.setState
您正在使用类)感到困惑。这些操作总是异步的,React 根据它认为的优先级来安排这些更改。
通过放置async
一个函数,您并不是说它突然异步,而是说它返回一个Promise
.
就 React 的工作方式而言,这并没有改变任何东西。如此有效地你handleSyncUpdate
和handleAsyncUpdate
React 基本相同,它们都触发异步操作(改变状态)。
setCount1(count => count + 1)
- 使用这个,你实际上是在使用最后一个状态值来更新,保证新值将是最后一个 + 1。
setCount1(count1 + 1)
- 在这种情况下,您使用的值在调用它的那一刻和 React 执行更新的那setState
一刻之间被另一个值改变。setState
我希望这有帮助
推荐阅读
- reactjs - 无法从客户端的 axios 响应中解析承诺
- gcc - ld 失败,因为 libselinux 未定义对 gettid@GLIBC_2.30 的引用
- python - SMOTE 用于平衡数据
- compression - 压缩 60 位字符串的最佳方法
- linux-mint - Linux-Mint-20 的协同作用
- javascript - 我如何将数据从屏幕上传递到 React Native 中的另一个?
- flutter - 解决异常:在 null 上调用了 getter 'iterator'
- r - 使用 echarts4r 测量颜色
- sql - 如何删除 varbinary 字符串中的前两个字符
- php - PHP 正则表达式匹配并在每个匹配中包含组(完全匹配)