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 - 修改GM_setValue和GM_getValue用于跨表通信: How to access Firefox Preferences variables?

javascript - 重新呈现 View 后,event.currentTarget.innerHTML 在 IE10 中为空

javascript - 新页面时保持打开子菜单

javascript - 如何在不发送太多请求的情况下通过前端在每次鼠标单击时更新我的​​数据库?

javascript - 我得到的空白页是什么?

node.js - 在另一个项目中使用一个 React 项目

JavaScript 函数 - 为什么它有效?

javascript - SVG 顶部的 React 单选按钮组的高级定位和大小调整

javascript - 将 Uint8Array 解码为 JSON

javascript - 自动滚动到 anchor 时的平滑效果