【问题标题】:How to use hooks as value of context provider in react js typescript如何在反应 js 打字稿中使用钩子作为上下文提供者的值
【发布时间】:2022-01-27 00:43:32
【问题描述】:

我创建了一个获取 API 的钩子,我需要在多个组件中调用该钩子,但是在每次重新获取 API 时挂载该组件时,我决定将该钩子作为 React 上下文提供程序的值调用,但 typescript将值传递给提供者说“{用户:{数据:任意;加载:布尔;错误:任意;} | {加载:任意;数据:任意;错误:任意;};注销:MutationTuple;登录:MutationTuple<...>;注册:MutationTuple<...>;}' 不可分配给类型“null”

const AuthContext = React.createContext(null);

export const AuthProvider: React.FC = ({ children }) => {
  return <AuthContext.Provider value={useAuthHook()}> // typescript not happy here
    {children}
  </AuthContext.Provider>
}

【问题讨论】:

    标签: javascript reactjs typescript react-native react-context


    【解决方案1】:

    在创建上下文时将钩子的返回类型作为类型参数传递

    const AuthContext = React.createContext<ReturnType<typeof useAuthHook> | null>(null);
    
    export const AuthProvider: React.FC = ({ children }) => {
      return <AuthContext.Provider value={useAuthHook()}>
        {children}
      </AuthContext.Provider>
    }
    

    在使用该上下文时

    export default function useAuth() {
      const context = React.useContext(AuthContext)!;
      if (context === undefined) {
        throw new Error("useAuth must be used within a AuthProvider");
      }
      return context;
    }
    

    在组件中

    export default function MyComponent() {
      const auth = useAuth();
      return (
          <div>Mycomponent</div>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      相关资源
      最近更新 更多