首页 > 解决方案 > 反应,打字稿,钩子。无法调用其类型缺少调用签名的表达式

问题描述

我是新来的反应钩子和相当新的打字稿。我一直在尝试使用钩子,特别是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 ,但会得到上面提到的错误。任何帮助将不胜感激!

标签: reactjstypescriptreact-hooks

解决方案


我想通了,所以我想我最好把它放在这里,以防其他人遇到同样的问题。
useContext(DrawerDispatch)返回一个对象并且dispatch是该对象的属性之一,因此const dispatch需要解构:
const { dispatch } = useContext(DrawerDispatch)会这样做。
或更好的变量命名:
const context = useContext(DrawerDispatch)然后将其称为 likecontext.dispatch而不是dispatch.


推荐阅读