简体   繁体   English

如何在反应 js typescript 中使用钩子作为上下文提供者的值

[英]How to use hooks as value of context provider in react js typescript

I had created a hook that fetches API and I need to call that hook in multiple components but while mounting that component every time the API is re-fetching so I had decided to call that hook as value as React context provider but typescript is not happy when passing value to the provider saying "{ user: { data: any; loading: boolean; error: any; } | { loading: any; data: any; error: any; }; logout: MutationTuple<any, OperationVariables, DefaultContext, ApolloCache>; login: MutationTuple<...>; signup: MutationTuple<...>; }' is not assignable to type 'null"我创建了一个获取 API 的钩子,我需要在多个组件中调用该钩子,但是在每次重新获取 API 时安装该组件时,所以我决定将该钩子称为 React 上下文提供程序的值,但 Z1E35BCBA205DBA1089C8FZ08 不快乐当向提供者传递值时说“{用户:{数据:任意;加载:boolean;错误:任意;} | {加载:任意;数据:任意;错误:任意;};注销:MutationTuple<任意,OperationVariables,DefaultContext , ApolloCache>; 登录: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>
}

pass the return type of hook as type argument while creating context在创建上下文时将钩子的返回类型作为类型参数传递

const AuthContext = React.createContext<ReturnType<typeof useAuthHook> | null>(null);

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

and while using that context在使用该上下文时

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

in a component在一个组件中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM