简体   繁体   English

React hook UseContext没有返回正确的值(根据typescript)

[英]React hook UseContext not returning correct value (according to typescript)

I have the following code that receives the dispatch method: 我有以下代码接收dispatch方法:

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

});

I use useContext like so; 我像这样使用useContext ;

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

When running mapDispatchToProps(dispatch); 运行mapDispatchToProps(dispatch); however I get the following error: 但是我收到以下错误:

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'.

It thinks dispatch is still an array… What's going on? 它认为dispatch仍然是阵列......发生了什么?

Turns out you have to declare the type for your context as follows: 事实证明,您必须为您的上下文声明类型,如下所示:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM