reactjs - 无法在反应打字稿中将函数作为上下文值传递
问题描述
这可能是一个菜鸟错误。但是我不能在 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
如果有人可以帮助我,那将非常有帮助。提前致谢。
解决方案
对不起,就像我说的,那是一个菜鸟的错误。就像@Brian Thompson 说我必须将它作为对象而不是对象传递。
推荐阅读
- reactjs - 如何在 Apollo 中为 refetchQueries 传递变量
- cassandra - Cassandra 前缀搜索
- pdo - 交易是否正确?
- mongodb - 无法执行类似 mongo 的查询
- c - C中的旋转程序
- go - 为什么 Golang 的 MD5 分布看起来不均匀?
- android - 如何修复与recyclerview重叠的视图?
- javascript - “错误:找不到 Opus 引擎。” 尝试播放 mp3 文件时 (discord.js)
- javascript - 在这种情况下,如何检查 json 数组的成员是否为空?
- apache - 如何在 apache httpd.conf 中添加注释而不是完整的行?