[英]What's the best way to batch state updates from async calls in React?
I understand from this post that React doesn't automatically batch state updates, in the case that an event is non-react
based ie setTimeout, Promise calls.我从这篇文章了解到,React 不会自动批处理 state 更新,如果事件
non-react
的,即 setTimeout、Promise 调用。 (In short any event from Web APIs.) (简而言之,来自 Web API 的任何事件。)
This differs from react-based
events, such as those from onClick events (etc), which are batched by react to limit renders.这不同于
react-based
事件,例如来自 onClick 事件(等)的事件,这些事件通过对限制渲染的反应进行批处理。 This is well illustrated in this answer , which essentially demonstrates that while this only triggers one render:这在这个答案中得到了很好的说明,它基本上证明了虽然这只会触发一个渲染:
function handleClickWithoutPromise() {
setA('aa');
setB('bb');
}
This will trigger two:这将触发两个:
function handleClickWithPromise() {
Promise.resolve().then(() => {
setA('aa');
setB('bb');
});
}
For me this is problematic, since on my first page load I sent a request to my back-end and receive various data that is used to update numerous discrete state objects.对我来说这是有问题的,因为在我的第一个页面加载时,我向后端发送了一个请求,并接收了用于更新大量离散 state 对象的各种数据。 This triggers a dozen re-renders, which is obviously not optimal.
这会触发十几个重新渲染,这显然不是最优的。
There are some options offered on different posts, but would appreciate some expert guidance as to which is best practice:不同的帖子提供了一些选项,但希望获得一些专家指导,了解最佳实践:
ReactDOM.unstable_batchedUpdates(() => {... })
, as recommended in this answerReactDOM.unstable_batchedUpdates(() => {... })
So, just in case no better answers are forthcoming, I found this article on Medium that shows a really good, simple example of the ReactDOM.unstable_batchedUpdates(() => {... })
working.因此,以防万一没有更好的答案出现,我 在 Medium 上找到了这篇文章,它展示了一个非常好的、简单的
ReactDOM.unstable_batchedUpdates(() => {... })
工作示例。 (You have to scroll a way down to the section: "How to force batching?" ). (您必须向下滚动到“如何强制批处理?”部分)。
The author also adds that:作者还补充说:
Although this function is supposedly “unstable”, React apparently intends to address this in the following versions.
尽管这个 function 被认为是“不稳定的”,但 React 显然打算在以下版本中解决这个问题。
“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.
“在未来的版本中(可能是 React 17 和更高版本),React 将默认批处理所有更新,因此您不必考虑这一点” ,根据 Dan Abramov 的说法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.