gpt4 book ai didi

javascript - 为什么异步函数中连续的 setState 调用没有被批处理?

转载 作者:行者123 更新时间:2023-11-29 20:31:55 52 4
gpt4 key购买 nike

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

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com