是否可以将typesafe-actions库与useContext和useReducer一起使用?

时间:2020-01-15 04:02:09

标签: react-hooks typesafe-actions

我想知道是否可以将typesafe-actions库与useContextuseReducer一起使用,以便我可以正确地TS键入上下文的dispatch属性(请参阅下面的???。

我有以下[缩写]设置:

// createAction is from typesafe-actions and TemplateActionTypes is my action type enum
const markClean = createAction(TemplateActionTypes.MARK_CLEAN)();

// an aggregation of action creators like the one above (some w/ arguments, some without)
const actions = {
  aBunchOfActions,
  moreActions
};

type AppActions = ActionType<typeof actions>; // ActionType is from typesafe-actions

const appReducer: Reducer<AppState, AppActions> = (
  state: AppState = ...,
  action: AppActions
): AppState => {
  ...
};

type AppContextType = {
  state: AppState; // my state tree interface
  dispatch: React.Dispatch<???>; // not sure of the right typings here
};

const AppContext = React.createContext<AppContextType>({ state: ..., dispatch: ??? });

// in a parent function component
// note that React has typings for the specified dispatch variable
const [state, dispatch] = useReducer(appReducer, myState);

// followed by the XXXContext.Provider logic...


// in child function component
const { dispatch } = useContext<AppContextType>(AppContext);
const handleMarkCleanClick = () => dispatch(markClean); // typings need to be right on my dispatcher so this is copasetic

0 个答案:

没有答案