【问题标题】:React Hooks with Typescript - Property does not exist on typeReact Hooks with Typescript - 类型上不存在属性
【发布时间】:2023-01-09 12:50:18
【问题描述】:

我有以下提供者/上下文...


interface Props {
  children: JSX.Element
}

const AuthContext = createContext({});

export const AuthProvider = ({ children }: Props) => {
  const [auth, setAuth] = useState({});

  return (
    <AuthContext.Provider value={{auth, setAuth}}>
      {children}
    </AuthContext.Provider>
  );
}

export default AuthContext;

我正在使用自定义挂钩来包装此上下文用法,如下所示:

import AuthContext from "../context/AuthProvider";

const useAuth = () => {
  return useContext(AuthContext);
}

export default useAuth;

然后,我尝试使用钩子:

const { setAuth } = useAuth();

我在 setAuth 上收到错误 - 属性 setAuth 在类型 {} 上不存在。

这是我在 es6 中编写的一些代码,我正在将其转换为 TS,但我不确定如何解决这个特定问题。

【问题讨论】:

  • 能否请您尝试设置上下文的默认值null,例如:createContext&lt;any&gt;(null);
  • 当您将空对象作为默认值传递给 createContext 时,类型将被推断为 {}。您需要传递一个泛型来告诉它什么类型实际上是。
  • @Thremulant 这是不必要的和误导的。为什么类型应该是any? OP 知道对象的形状,{} 是比null 更合理的默认值。
  • @JaredSmith 明白了。在那种情况下,它应该是createContext&lt;IAuthContext&gt;,其中新接口包括authsetAuth
  • @Thremulant 正确!

标签: reactjs typescript


【解决方案1】:

您应该向 createContext 函数添加一个通用参数:

import { useState, createContext, Dispatch, SetStateAction } from 'react';

interface Auth {
  // The properties you expect on the `auth` variable
}

interface AuthContextInterface {
  auth: Auth
  setAuth: Dispatch<SetStateAction<Auth>>
}

使用 TypeScript,您还需要提供一个与 AuthContextInterface 类型匹配的初始值,它可以是一组默认值或只是 undefined! 来告诉 TypeScript 您确定稍后会覆盖它:

const AuthContext = createContext<AuthContextInterface>({
  auth: { /* an initial value for auth */ },
  setAuth: () => {}
});

【讨论】:

  • 把我带到了我需要去的地方。谢谢!
【解决方案2】:

由于有时我没有上下文的初始值,我建议:

interface IAuthContext {
  auth: IAuth // Whatever you need to add here
  setAuth: (auth: IAuth) => void
}
const AuthContext = createContext<IAuthContext | null>(null);

【讨论】:

    【解决方案3】:

    要解决此问题,您可以为包含 auth 对象和 setAuth 函数的 createContext 函数提供适当的默认值。例如:

        const AuthContext = createContext({
          auth: {},
          setAuth: (auth: any) => {}
        });
    

    这应该允许您从 useAuth 挂钩返回的值中解构 setAuth 函数,而不会出现错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 2020-05-21
      • 2020-05-15
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 2018-07-31
      相关资源
      最近更新 更多