Мне сложно отладить этот код, просто взглянув на него, но я собираюсь показать вам очень похожий код, который у меня есть, в надежде, что вы сможете что-то из него извлечь. Главное, что я использовал typesafe-действия: https://github.com/piotrwitek/typesafe-actions
index.tsx:
import React, { createContext, useContext, useEffect, useReducer } from 'react';
import { ActionType } from 'typesafe-actions';
import * as actions from './app.actions';
import * as userActions from './user/actions';
import * as fromUser from './user/reducer';
interface State {
user: fromUser.State,
}
const appReducer = (state: State, action: ActionType<typeof actions>) => ({
user: fromUser.reducer(state.user, action as ActionType<typeof userActions>),
});
const initialState: State = {
user: fromUser.initialState,
};
const StateContext = createContext(initialState);
const DispatchContext = createContext((_: ActionType<typeof actions>) => { });
interface ProviderProps { children: React.ReactNode }
export const StoreProvider: React.FC<ProviderProps> = ({ children }) => {
const [state, dispatch] = useReducer(appReducer, initialState);
useEffect(() => {
dispatch(actions.appStart());
return () => dispatch(actions.appEnd());
}, []);
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
{children}
</DispatchContext.Provider>
</StateContext.Provider>
);
};
export function useStore() {
return useContext(StateContext);
}
export function useDispatch() {
return useContext(DispatchContext);
}
. / User / actions:
export const ADD_USER = 'user/ADD_USER';
export const addUser = (user: string) => ({
type: ADD_USER,
user,
} as const);
export const REMOVE_USER = 'user/REMOVE_USER';
export const removeUser = () => ({
type: REMOVE_USER,
} as const);
. / Пользователь / редуктор:
import { ActionType } from 'typesafe-actions';
import * as actions from './actions';
export interface State {
userName: string | null,
}
export const initialState: State = {
userName: null,
};
export const reducer = (state = initialState, action: ActionType<typeof actions>): State => {
switch (action.type) {
case actions.ADD_USER: {
return {
userName: action.user,
};
}
case actions.REMOVE_USER: {
return {
userName: null,
};
}
default: return state;
}
};