【发布时间】:2020-11-25 17:12:25
【问题描述】:
这可能是一个菜鸟错误。但是我不能在 createContext 对象中声明一个函数。这是我的代码。
import { createContext, useEffect, useState } from "react";
import { verifyJWTToken } from "../utils/functions";
type authValues = {
isAuthenticated: boolean;
user: {};
toggleAuth: () => void;
};
export const AuthContext = createContext<Partial<authValues>>({});
interface authContextProps {}
const AuthContextProvider: React.FC<authContextProps> = (props) => {
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const [user, setUser] = useState({});
const toggleAuth = () => setIsAuthenticated(!isAuthenticated);
useEffect(() => {
const localData = localStorage.getItem("authToken");
if (localData) {
const res = verifyJWTToken(JSON.parse(localData));
if ((res as any).err) {
console.log("Not Authenticated");
} else if ((res as any).user) {
setIsAuthenticated(true);
setUser((res as any).user);
}
}
}, []);
return (
<AuthContext.Provider
value={{ isAuthenticated, toggleAuth: { toggleAuth }, user }}
>
{props.children}
</AuthContext.Provider>
);
};
export default AuthContextProvider;
这里的问题是我不能将函数 toggleAuth 作为 AuthContextProvider 的值发送。 vscode 错误提示
Type '{ toggleAuth: () => void; }' is not assignable to type '() => void'.
Object literal may only specify known properties, and 'toggleAuth' does not exist in type '() => void'.ts(2322)
AuthContext.tsx(7, 3): The expected type comes from property 'toggleAuth' which is declared here on type 'Partial<authValues>'
Reactjs 错误提示
Unhandled Runtime Error
TypeError: toggleAuth is not a function
如果有人可以帮助我,那将非常有帮助。提前致谢。
【问题讨论】:
-
好吧,你不是在传递一个函数,而是传递一个具有函数属性的对象。它只需要
toggleAuth: toggleAuth。 -
哎呀,就像我说的,这是一个菜鸟的错误,谢谢顺便说一句
-
你能看看那个useEffect函数吗?这给我带来了很多问题
标签: reactjs react-context react-typescript