【问题标题】:How do I add type definitions for React's useContext?如何为 React 的 useContext 添加类型定义?
【发布时间】:2021-08-05 23:45:29
【问题描述】:
interface AppState {
 jwt: string | null,
 isSignedIn: boolean
 isLoading : boolean;
 newUser : boolean;
 avatar : Avatar | null;
 alerts : SnackBarAlert[];
}
const initialState : AppState = { isLoading : true, isSignedIn : false, newUser : false, hero : null, alerts : [], jwt : null };

const store = createContext(initialState);
const { state, dispatch } = useContext(store);

当我将鼠标悬停在状态或调度上时,我得到“属性 '状态' 不存在于类型 'AppState' 上”。和“'AppState' 类型上不存在属性 'dispatch'。”

我心想'哦,我需要告诉 useContext 商店是什么类型。但是当我试图描述这家商店时......

interface Store {
  state: AppState
  dispatch: <Payload = {}>(action: Action<Payload>) => void
} 
const { state, dispatch } = useContext<Store>(store);

'store' 突出显示告诉我: “‘上下文’类型的参数不能分配给‘上下文’类型的参数。 'Provider.propTypes.value' 的类型在这些类型之间不兼容。 类型“验证器”不可分配给类型“验证器”。 类型 'AppState' 不可分配给类型 'Store'。”

我在这里做错了什么?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    我只是查看了类型定义:

    /**
     * Accepts a context object (the value returned from `React.createContext`) and returns the current
     * context value, as given by the nearest context provider for the given context.
     *
     * @version 16.8.0
     * @see https://reactjs.org/docs/hooks-reference.html#usecontext
     */
    function useContext<T>(context: Context<T>/*, (not public API) observedBits?: number|boolean */): T;
    

    这意味着您的状态由T 表示。你通过调用React.createContext 得到Context&lt;T&gt;,它作为参数context 传递给函数useContextuseContext 返回给定状态 T 本身。在您的情况下,状态由

    给出
    interface AppState {
      jwt: string | null,
      isSignedIn: boolean
      isLoading : boolean;
      newUser : boolean;
      avatar : Avatar | null;
      alerts : SnackBarAlert[];
    }
    

    但是通过使用解构赋值 const { state, dispatch } = useContext&lt;Store&gt;(store);,您假设 statedispatch 是您的状态的一部分,根据上面的定义,这是不正确的。

    因此您不必为useContext 添加类型定义。它是自动推断的。你只需要尊重它所推断的。

    这也意味着你必须自己定义并提供一个dispatch 函数,如果你想提供一种方法来改变你的状态中的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-24
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 2011-04-27
      • 2011-08-10
      • 2020-08-13
      相关资源
      最近更新 更多