首页 > 解决方案 > TypeScript React 上下文 API

问题描述

我创建了一个用户上下文 API(此处的代码:https ://pastebin.pl/view/e0b5e0f4 ),然后我可以像这样阅读它:

const { state: { user }, dispatch} = useUserContext();

但我想这样做(数组而不是对象):

const [{ user }, dispatch] = useUserContext();

所以我将 UserProvider 更改为:

export const UserProvider: React.FC<UserProviderProps> = ({
  reducer,
  initialState,
  children,
}) => (
  <UserContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </UserContext.Provider>
);

我收到提示错误消息:

Type '[UserProps, Dispatch<UserActions>]' is not assignable to type 'UserContextProps'.ts(2322)
index.d.ts(337, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<UserContextProps>'

我对 TypeScript 有点陌生,我被困在这里

标签: javascriptreactjstypescriptredux

解决方案


推荐阅读