[英]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.