小编典典

在Typescript中反应createContext问题?

reactjs

所以我在React Context + Typescript上遇到了一个很奇怪的问题。

工作实例

在上面的示例中,您可以看到我正在尝试做的实际工作。本质上,我正在使用新的useContext方法管理状态,并且它运行完美。

但是,当我尝试在盒子上执行此操作时,似乎无法找到通过useReducer传递的状态值。

export function AdminStoreProvider(props: any) {
const [state, dispatch] = useReducer(reducer, initialState);
// state.isAuth is avail here
// state.user is avail here
const value = { state, dispatch };
// value.state.isAuth is avail here
return (
    /* value does not contain state once applied to the value prop */
    <AdminStore.Provider value={value}>{props.children} 
    </AdminStore.Provider>
   );
}

错误信息:

Type '{ state: { isAuth: boolean; user: string; }; dispatch: 
Dispatch<Actions>; }' is missing the following properties from type 
'IState': isAuth, user

请记住,我正在使用的代码正是我在盒子上使用的代码,我什至从沙盒下载了代码并尝试运行它,但它不起作用。

我正在使用VSCode 1.31

我设法推断出,如果我从以下位置更改创建上下文的方式:

export const AdminStore = React.createContext(initialState);

export const AdminStore = React.createContext(null);

value属性不再引发该错误。

但是,现在useContext返回一个错误:状态不存在为null。同样,如果我将context的defaultState设置为{}。

当然,如果我

React.createContext();

然后TS大喊没有提供defaultValue。

在沙箱中,创建上下文对象的所有3个版本都可以正常工作。

在此先感谢您的任何建议。


阅读 1498

收藏
2020-07-22

共1个答案

小编典典

看来的defaultValue
React.createContext应为以下类型:

interface IContextProps {
  state: IState;
  dispatch: ({type}:{type:string}) => void;
}

一旦Context为此类型创建了对象,例如:

export const AdminStore = React.createContext({} as IContextProps);

提供者React组件应该不再抱怨该错误。

以下是更改列表:

admin-store.tsx

import React, { useReducer } from "react";
import { initialState, IState, reducer } from "./reducer";


interface IContextProps {
  state: IState;
  dispatch: ({type}:{type:string}) => void;
}


export const AdminStore = React.createContext({} as IContextProps);

export function AdminStoreProvider(props: any) {
  const [state, dispatch] = useReducer(reducer, initialState);

  const value = { state, dispatch };
  return (
    <AdminStore.Provider value={value}>{props.children}</AdminStore.Provider>
  );
}
2020-07-22