reactjs - 反应,打字稿,钩子。无法调用其类型缺少调用签名的表达式
问题描述
我是新来的反应钩子和相当新的打字稿。我一直在尝试使用钩子,特别是useContext
钩子来管理全局状态(我很欣赏这个例子,它可能有点矫枉过正,但我的目标只是能够真正理解它)。我遵循了几个不同的示例,但没有使用打字稿,现在出现此错误:
Cannot invoke an expression whose type lacks a call signature. Type 'ContextProps' has no compatible call signatures.
我在这里查看了多个其他问题,这些问题解释了解决方案(关于签名上的联合),但我无法理解与我的代码相关的问题。
这是我代码的简化版本(请原谅,因为我还在学习:)),但我在以下handleOpenDrawer
函数中收到错误MainPage.tsx
:
应用程序.tsx
import React, { createContext, Dispatch, useReducer } from 'react';
import MainPage from './MainPage';
interface ContextProps {
drawerState: DrawerState;
drawerDispatch: Dispatch<DrawerActions>;
}
interface DrawerState {
open: boolean;
}
const initialDrawerPosition:DrawerState = {
open: false,
};
interface DrawerActions {
type: 'OPEN_DRAWER' | 'CLOSE_DRAWER';
}
const reducer = (state:DrawerState, action:DrawerActions) => {
switch (action.type) {
case 'OPEN_DRAWER':
return {
...state,
open: true,
};
case 'CLOSE_DRAWER':
return {
...state,
open: false,
};
default:
return state;
}
};
export const DrawerDispatch = createContext({} as ContextProps);
export default function App() {
const [ drawerState, drawerDispatch ] = useReducer(reducer, initialDrawerPosition);
const value = { drawerState, drawerDispatch };
return (
<DrawerDispatch.Provider value={value}>
<MainPage />
</DrawerDispatch.Provider>
);
}
主页.tsx
import { useContext } from 'react';
import { DrawerDispatch } from './App';
export default function App() {
const dispatch = useContext(DrawerDispatch);
const handleOpenDrawer = () => {
dispatch({ type: 'OPEN_DRAWER' });
};
return (
<button onClick={handleOpenDrawer}>
Click me
</button>
);
}
我希望能够state.open
使用调度将 更新为 true ,但会得到上面提到的错误。任何帮助将不胜感激!
解决方案
我想通了,所以我想我最好把它放在这里,以防其他人遇到同样的问题。
useContext(DrawerDispatch)
返回一个对象并且dispatch
是该对象的属性之一,因此const dispatch
需要解构:
const { dispatch } = useContext(DrawerDispatch)
会这样做。
或更好的变量命名:
const context = useContext(DrawerDispatch)
然后将其称为 likecontext.dispatch
而不是dispatch
.
推荐阅读
- ios - 从 Any 投射时 UIColor 子类崩溃?
- plugins - 如何在页面上添加两个(或多个)相同类型的 AJS.MultiSelect 字段
- asp.net-core - 是否可以从 MassTransit 的错误队列中读取和删除消息
- amazon-web-services - CloudFormation 模板相当于添加“其他 AWS 账户的访问权限”
- installation - 蓝色棱镜并排或安装多个版本(不同)的可能性/方法
- mysql - MySQL 对似乎在工作台上运行良好的查询给出错误
- html - 在服务器上部署网站后,相对链接不起作用
- maven - Docker 构建失败“复制失败:未指定源文件”
- git - Git rebase 功能分支搞乱了对开发/主分支的拉取请求中的提交
- google-apps-script - 复制行的范围而不是整行 - 应用脚本