React createContext issue in Typescript?

前端 未结 2 579
一个人的身影
一个人的身影 2021-02-02 08:33

So I\'m having a very weird issue with React Context + Typescript.

Working example

In the above example, you can see what I\'m trying to do actually work. Essen

2条回答
  •  广开言路
    2021-02-02 09:12

    It appears defaultValue value for React.createContext is expected to be of type:

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

    Once Context object is created for this type, for example like this:

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

    Provider React component should no longer complain about the error.

    Here is the list of changes:

    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 (
        {props.children}
      );
    }
    

提交回复
热议问题