javascript - 为什么异步函数中的连续 setState 调用不进行批处理?

标签 javascript reactjs

所以我知道 setState 调用在 React 事件处理程序中进行批处理以提高性能,但我不明白的是为什么它们不在异步回调中对 setState 调用进行批处理。

例如: 假设我在其中一个钩子(Hook)中有以下代码。

fetch(url).then(res => res.json())
then((data)=>{
  setLoader(false);
  setData(data);
})

这两个 setState 调用将导致两个不同的渲染,即使它们在某种程度上是连续或同步的。

我想了解为什么我们不能至少批处理这些彼此相邻的 setState 调用。这是由于技术限制还是有原因选择不这样做?

最佳答案

本期讨论何时对 setState 进行批处理以及何时不进行批处理:

https://github.com/facebook/react/issues/14259

总结一下:

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 wraps your event handlers in a call to unstable_batchedUpdates(), so that your handler runs inside a callback. Any state updates triggered inside that callback will be batched. Any state updates triggered outside that callback will not be batched. Timeouts, promises, and async functions will end up executing outside that callback, and therefore not be batched.

该线程还提供了一些关于如何使用 useReducer 而不是 useState 解决此“问题”的建议。这是一个例子,虽然我还没有尝试过它是否有效:

const [ state, dispatch, batch ] = useReducer(reducer, initialState);

batch(() => {
  dispatch(..);
  dispatch(..);
  // etc..
})

关于javascript - 为什么异步函数中的连续 setState 调用不进行批处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57781683/

相关文章:

无限循环中的 Javascript 警报消息

JavaScript 游戏 - 无法通过 0.5 像素偏移和错误边界渲染进入中心圆圈

reactjs - 在一行中获取按钮和输入字段

html - 在 React 中渲染 HTMLDivElement

javascript - Nodejs 无法从 html 引用中找到图像

javascript - jquery 附加和 jquery html 在 IE 7 或 8 中不起作用

reactjs - 如何在 React Native 调试器上安装 debuggerWorker.js?

reactjs - useEffect 模拟 componentWillUnmount 不返回更新状态

javascript - React 应用程序加载主页而不是所需页面

javascript - 像真正的 html 元素而不是 Canvas 或 svg 一样渲染 pdf.js 页面?