我从 this post 了解到如果事件是 non-react
,React 不会自动批量更新状态。基于即 setTimeout,Promise 调用。 (简而言之,来自 Web API 的任何事件。)
这与 react-based
不同。事件,例如来自 onClick 事件(等)的事件,这些事件通过对限制渲染的 react 进行批处理。这在 this answer 中有很好的说明。 ,这从本质上表明,虽然这只会触发一次渲染:
function handleClickWithoutPromise() {
setA('aa');
setB('bb');
}
这将触发两个: function handleClickWithPromise() {
Promise.resolve().then(() => {
setA('aa');
setB('bb');
});
}
对我来说这是有问题的,因为在我的第一个页面加载时,我向后端发送了一个请求,并接收到用于更新大量离散状态对象的各种数据。这会触发十几个重新渲染,这显然不是最优的。不同的帖子提供了一些选项,但希望获得一些专家指导,了解最佳实践:
ReactDOM.unstable_batchedUpdates(() => { ... })
,如 this answer 中的建议最佳答案
所以,以防万一没有更好的答案,我发现了这个 article on Medium这显示了 ReactDOM.unstable_batchedUpdates(() => { ... })
的一个非常好的简单示例在职的。 (您必须向下滚动到以下部分:“如何强制批处理?”)。
作者还补充说:
Although this function is supposedly “unstable”, React apparently intends to address this in the following versions.
“In future versions (probably React 17 and later), React will batch all updates by default so you won’t have to think about this”, according to Dan Abramov.
关于javascript - 从 React 中的异步调用批量状态更新的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66471772/