【问题标题】:React, Typescript, Hooks. Cannot invoke an expression whose type lacks a call signature反应,打字稿,钩子。无法调用类型缺少调用签名的表达式
【发布时间】:2019-07-03 17:58:13
【问题描述】:

我是反应钩子的新手,对打字稿也很陌生。我一直在尝试使用钩子,特别是 useContext 钩子来管理全局状态(我很欣赏这个例子,它可能有点矫枉过正,但我​​的目标只是能够真正理解它)。 我遵循了几个不同的示例,但没有使用 typescript,现在出现此错误:

Cannot invoke an expression whose type lacks a call signature. Type 'ContextProps' has no compatible call signatures.

我在这里查看了多个其他问题来解释解决方案(关于签名上的联合),但我无法理解与我的代码相关的问题。

这是我代码的简化版本(请原谅,因为我还在学习 :)),但我在 MainPage.tsx 中的 handleOpenDrawer 函数上收到错误:

App.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>
    );

}

MainPage.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,但会收到上述错误。 任何帮助将不胜感激!

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 2017-09-01
      • 2017-12-19
      • 2021-02-06
      • 2017-07-14
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多