React hook UseContext 不返回正确的值(根据打字稿)



我有以下代码接收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仍然是一个数组...这是怎么回事?

事实证明,

您必须按如下方式声明上下文的类型:

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

而不是export const AppContext = React.createContext<Array<[AppState, Dispatch<AppAction>]> | null>(null);

相关内容

  • 没有找到相关文章

最新更新