反应挂钩UseContext没有返回正确的值(根据打字稿)

时间:2019-03-28 15:07:41

标签: javascript reactjs typescript react-hooks

我有以下代码接收dispatch方法:

const mapDispatchToProps = (dispatch: React.Dispatch<AppAction>) => ({

});

我像这样使用useContext

    const appContext = useContext(AppContext);
    const [state, dispatch] = appContext;

运行mapDispatchToProps(dispatch);时,出现以下错误:

Error:(28, 24) TS2345: Argument of type '[AppState, Dispatch<AppAction>]' is not assignable to parameter of type 'Dispatch<AppAction>'. Type '[AppState, Dispatch<AppAction>]' provides no match for the signature '(value: AppAction): void'.

它认为dispatch仍然是一个数组……发生了什么事?

1 个答案:

答案 0 :(得分:0)

原来,您必须为上下文声明类型,如下所示:

$spread(payload)

代替export const AppContext = React.createContext<[AppState, Dispatch<AppAction>] | null>(null);