自React 18以来,状态更新自动批量处理。当使用Redux时,也使用batches。但是,在使用异步调度调用时,它似乎不起作用。例如,对于形实转换:
const incrementAsync = createAsyncThunk("incrementAsync", (_, { dispatch }) => {
setTimeout(() => {
dispatch(increment());
}, 1000);
});
字符串
以下操作将使组件重新渲染三次(但在视觉上计数器只更改一次):
const increment = () => {
dispatch(incrementAsync());
dispatch(incrementAsync());
dispatch(incrementAsync());
};
型
CodeSandbox demo的
我不知道这是否是预期的行为,但是**我如何才能批量更新这些更新?**我希望我的组件只重新渲染一次,不管更新的次数。
请注意:
我只为这个问题做了这些片段,我的代码与简单的计数器无关,我需要调用异步。
1条答案
按热度按时间jxct1oxe1#
可以使用
autoBatchEnhancer
一个Redux商店增强器,它在一行中查找一个或多个“低优先级”的已调度操作,并对回调进行排队以在延迟时运行订阅者通知。然后,它会在队列回调运行时或下一个“正常优先级”操作调度时(以先发生者为准)通知订阅者。
counterSlice.js
:字符串
store.js
:型
codesandbox的