redux 如何在createSlice()中按类型调用动作

bvjxkvbb  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(186)

切片中的动作有类型。可以像dispatch({type:'filter/category', payload:'change state'})?x1c 0d1x这样调用此动作
我试过使用dispatch({type:'filter/category', payload:'change state'}),但是状态没有变化。有没有办法在redux/toolkit中实现,或者我应该把它移植到redux中?

更新工作存储库:https://gitlab.com/witekmikolajczak/dynamic_reducers

我按照文件:https://redux.js.org/usage/code-splitting

CODE我的减速器代码(文档)

export interface GenericState<T> {}
export const createGenericSlice = <T, Reducers extends SliceCaseReducers<GenericState<T>>>({
  name = 'filter',
  initialState,
  reducers,
}: {
  name: string;
  initialState: GenericState<T>;
  reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>;
}) => {
  return createSlice({
    name,
    initialState,
    reducers: {
      loadFilterOptions: (state, action: PayloadAction<any>) => {
        state = action.payload;
        return state;
      },
      ...reducers,
    },
  });
};

export const wrappedSlice = (reducers: any, initialState: any) =>
  createGenericSlice({
    name: 'filter',
    initialState: initialState as GenericState<[]>,
    reducers: {
      ...reducers,
    },
  });

合并减速器

import { combineReducers } from 'redux';
// api

const initialReducers = {};
export const createReducer = (asyncReducers = {}) => {
  return combineReducers({
    ...initialReducers,
    ...asyncReducers,
  });
};

export default createReducer;

存储

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import createReducer from './rootReducer';

export function initStore() {
  return configureStore({
    reducer: createReducer(),
    middleware: (getDefaultMiddleware) => [...getDefaultMiddleware()],
  });
}
const store = initStore();

export function injectAsyncReducer(key: any, asyncReducer: any) {
  asyncReducer[key] = asyncReducer;
  store.replaceReducer(createReducer(asyncReducer));
}

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, RootState, unknown, Action<string>>;

export default store;

在大钩内增加新的减速器

injectAsyncReducer('test', this.reducerCollection.caseReducers.category);

**问题:**如何按类型分配操作,例如。

dispatch({type:"filter/load", payload:data})
wvt8vs2t

wvt8vs2t1#

看起来您在这里使用的是redux工具包,但是您试图通过类型直接调度它。我建议您使用createSlice中reducer属性提供的同步函数(我再次假设您使用的是RTK)。

const filterSlice = createSlice({
  name: 'filter',
  initialState,
  reducers: {
    filterCategory: (state, action) => {
      state.category = action.payload;
    }
  }
});

export const { filterCategory } = filterSlice.actions;
export default filterSlice.reducer;

然后直接调度它,只需使用

dispatch(filterCategory());

希望这对你有帮助,伙计,不要犹豫,要更多。

相关问题