所以我知道 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/