redux 我如何使批处理与异步分派调用一起工作?

ctzwtxfj  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(89)

自React 18以来,状态更新自动批量处理。当使用Redux时,也使用batches。但是,在使用异步调度调用时,它似乎不起作用。例如,对于形实转换:

const incrementAsync = createAsyncThunk("incrementAsync", (_, { dispatch }) => {
  setTimeout(() => {
    dispatch(increment());
  }, 1000);
});

字符串
以下操作将使组件重新渲染三次(但在视觉上计数器只更改一次):

const increment = () => {
  dispatch(incrementAsync());
  dispatch(incrementAsync());
  dispatch(incrementAsync());
};


CodeSandbox demo
我不知道这是否是预期的行为,但是**我如何才能批量更新这些更新?**我希望我的组件只重新渲染一次,不管更新的次数。

请注意:

我只为这个问题做了这些片段,我的代码与简单的计数器无关,我需要调用异步。

jxct1oxe

jxct1oxe1#

  • @reduxjs/toolkit:1.9.5 *

可以使用autoBatchEnhancer
一个Redux商店增强器,它在一行中查找一个或多个“低优先级”的已调度操作,并对回调进行排队以在延迟时运行订阅者通知。然后,它会在队列回调运行时或下一个“正常优先级”操作调度时(以先发生者为准)通知订阅者。
counterSlice.js

import { createSlice, createAsyncThunk, prepareAutoBatched, SHOULD_AUTOBATCH } from '@reduxjs/toolkit';

export const incrementAsync = createAsyncThunk('incrementAsync', (_, { dispatch }) => {
    setTimeout(() => {
        dispatch(increment());
    }, 1000);
});

export const counterSlice = createSlice({
    name: 'counter',
    initialState: {
        value: 0,
    },
    reducers: {
        increment: {
            reducer: (state, action) => {
                console.log('action: ', action);
                state.value += 1;
            },
            prepare: prepareAutoBatched(),
        },
    }
});

export const { increment } = counterSlice.actions;

export const selectCount = (state) => state.counter.value;

export default counterSlice.reducer;

字符串
store.js

import { configureStore, autoBatchEnhancer } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export default configureStore({
    reducer: {
        counter: counterReducer,
    },
    enhancers: (existingEnhancers) => {
        // Add the autobatch enhancer to the store setup
        return existingEnhancers.concat(autoBatchEnhancer());
    },
});


codesandbox

相关问题