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

I'm trying to use createContext with useReducer and have some trouble

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

所有帮助将不胜感激

这是我的商店

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
评论