![](/img/trans.png)
[英]React, Typescript, Hooks - Property 'state' does not exist on type
[英]React Hooks with Typescript - Property does not exist on type
我有以下提供者/上下文...
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,但我不确定如何解决这个特定问题。
您应该向createContext
function 添加一个通用参数:
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: () => {}
});
要解决此问题,您可以为 createContext function 提供适当的默认值,其中包括 auth object 和 setAuth function。例如:
const AuthContext = createContext({
auth: {},
setAuth: (auth: any) => {}
});
这应该允许您从 useAuth 挂钩返回的值中解构 setAuth function 而不会出现错误。
块引用
由于有时我没有上下文的初始值,我建议:
interface IAuthContext {
auth: IAuth // Whatever you need to add here
setAuth: (auth: IAuth) => void
}
const AuthContext = createContext<IAuthContext | null>(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.