如何在typescript中正确键入简单的useReducer和Contextapi



我正在尝试从zeit中作为状态管理器的Context api的一个官方但简单的示例,但我得到了这样的类型错误,即"此表达式不可调用。类型‘{}’没有调用签名。"当我试图从useDispatchViewer调用dispatch时,因为我的createcontext({})只是一个空对象?那它需要什么。你不能让它空着,就像例子或打字稿会对你大喊大叫一样。

import { Reducer, createContext, useReducer, FC, useContext } from "react";
import { Viewer } from "../generated/graphql";
const ViewerContext = createContext({});
const DispatchContext = createContext({});
export enum ActionType {
setViewer = "SET_VIEWER",
getViewer = "GET_VIEWER"
}
export const initialViewer: Viewer = {
name: null,
image: null,
email: null
};
export const viewerReducer: Reducer<Viewer, any> = (viewer, action) => {
switch (action.type) {
case ActionType.setViewer:
return action.payload;
case ActionType.getViewer:
return viewer;
default:
throw new Error(`Unknown action: ${action.type}`);
}
};
export const ViewerProvider: FC = ({ children }) => {
const [viewer, dispatch] = useReducer(viewerReducer, initialViewer);
return (
<DispatchContext.Provider value={dispatch}>
<ViewerContext.Provider value={viewer}>{children}</ViewerContext.Provider>
</DispatchContext.Provider>
);
};
export const useViewer = () => useContext(ViewerContext);
export const useDispatchViewer = () => useContext(DispatchContext);

经过一段紧张的谷歌搜索,我在这里找到了答案。

export type Action =
| { type: "SET_VIEWER"; payload: any };
const ViewerContext = createContext(initialViewer);
const DispatchContext = createContext((() => {}) as Dispatch<Action>);

相关内容

  • 没有找到相关文章

最新更新