【发布时间】: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