gpt4 book ai didi

javascript - 为什么调用 useState 钩子(Hook)的 set 函数会立即应用于异步函数?

转载 作者:行者123 更新时间:2023-12-05 00:29:09 27 4
gpt4 key购买 nike

在同步和异步函数中调用 useState Hook 的多个集合函数时,我遇到了不同的行为。

function Test() {
console.log('app rendering starts.');
const [a, setA] = useState(1);
const [b, setB] = useState(11);
const updateState = () => {
console.log('\tupdating a starts.');
setA(2);
console.log('\tupdating a ends.');
console.log('\tupdating b starts.');
setB(12);
console.log('\tupdating b ends.');
};
console.log('app rendering ends.');
return (
<div className="App">
<div>a is {a}</div>
<div>b is {b}</div>
<button onClick={() => {
console.log('--------------sync click--------------');
updateState();
}}>Update State a & b Sync</button>
<button onClick={() => {
console.log('--------------async click--------------');
setTimeout(updateState, 0)
}}>Update State a & b Async</button>
</div>
);
}
两个按钮执行相同的代码,但方式不同。
同步按钮结果:
app rendering starts.
app rendering ends.
--------------sync click--------------
updating a starts.
updating a ends.
updating b starts.
updating b ends.
app rendering starts.
app rendering ends.
异步按钮结果:
app rendering starts.
app rendering ends.
--------------async click--------------
updating a starts.
app rendering starts.
app rendering ends.
updating a ends.
updating b starts.
app rendering starts.
app rendering ends.
updating b ends.
这是理想的行为吗?
如何在异步函数中获得同步结果?
我在官方文档中找不到任何提示。
任何帮助,将不胜感激。
谢谢!

最佳答案

根据Github discussions,这似乎是一个已知事实。 .
我认为其中一条评论非常不言自明:

React currently will batch state updates if they're triggered from within a React-based event, like a button click or input change. It will not batch updates if they're triggered outside of a React event handler, like a setTimeout().


React 内部使用 unstable_batchedUpdates() .您可以传入一个回调函数,并在其中进行批量状态更新。对于超时、 promise 和异步函数,这不会自动发生。因此它们是从回调外部调用的,并且它们内部的状态更新不会被批处理。
import { unstable_batchedUpdates } from "react-dom";
const updateState = () => {
unstable_batchedUpdates(() => {
console.log("\tupdating a starts.");
setA(2);
console.log("\tupdating a ends.");
console.log("\tupdating b starts.");
setB(12);
console.log("\tupdating b ends.");
});
};

Sandbox Link

关于javascript - 为什么调用 useState 钩子(Hook)的 set 函数会立即应用于异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70142091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com