如何使用createContext和useReducer管理多个Reducer

时间:2020-05-17 10:12:45

标签: reactjs typescript

我正在尝试将createContextuseReducer一起使用,并且遇到一些麻烦

我正在分派两个动作,并且两个动作都将其有效负载存储在状态中的同一位置,而不是存储到它们自己的位置。

所有帮助将不胜感激

这是我的商店

import React, { createContext, useReducer, Dispatch } from 'react';

import { InitialStateType } from './types';

import { citiesReducer, CitiesActions } from './citiesReducer';
import { LoadingActions, loadingReducer } from './loadingReducer';

const initialState: InitialStateType = {
  cities: [],
  loading: false,
};

const store = createContext<{
  state: InitialStateType;
  dispatch: Dispatch<CitiesActions | LoadingActions>;
}>({
  state: initialState,
  dispatch: () => {},
});
const { Provider } = store;

const mainReducer = (
  { cities, loading }: InitialStateType,
  action: LoadingActions | CitiesActions,
) => ({
  cities: citiesReducer(cities, action),
  loading: loadingReducer(loading, action),
});

const StateProvider = ({ children }: any): React.ReactElement => {
  const [state, dispatch] = useReducer<any>(mainReducer, initialState);

  return <Provider value={{ state, dispatch }}>{children}</Provider>;
};

export { store, StateProvider };

两个减速器

import { ActionTypes } from './types';

export type CitiesActions = {
  type: ActionTypes.SET_CITIES_DATA;
  payload: [];
};

export const citiesReducer = (state: [], action: CitiesActions) => {
  switch (action.type) {
    case action.type:
      return (state = action.payload);
    default:
      return state;
  }
};

import { ActionTypes } from './types';

export type LoadingActions = {
  type: ActionTypes.LOADING;
  payload: boolean;
};

export const loadingReducer = (state: boolean, action: LoadingActions) => {
  switch (action.type) {
    case action.type:
      return (state = action.payload);
    default:
      return state;
  }
};

在这里,我要一次又一次地调度动作

dispatch({ type: ActionTypes.SET_CITIES_DATA, payload: result });
dispatch({ type: ActionTypes.LOADING, payload: false });

结果,我进入了状态

cities: false
loading: false

代替

cities: [data],
loading: false

1 个答案:

答案 0 :(得分:1)

处理减速器时,您需要指定操作,而不要在switch语句中使用case action.type这样的情况,否则考虑到您调度的所有减速器将使用什么操作并设置有效负载。在这种情况下,将为所有状态设置最后的动作数据

export type CitiesActions = {
  type: ActionTypes.SET_CITIES_DATA;
  payload: [];
};

export const citiesReducer = (state: [], action: CitiesActions) => {
  switch (action.type) {
    case ActionTypes.SET_CITIES_DATA: // specify the action here
      return (state = action.payload);
    default:
      return state;
  }
};

import { ActionTypes } from './types';

export type LoadingActions = {
  type: ActionTypes.LOADING;
  payload: boolean;
};

export const loadingReducer = (state: boolean, action: LoadingActions) => {
  switch (action.type) {
    case ActionTypes.LOADING: // Specify the action here
      return (state = action.payload);
    default:
      return state;
  }
};