首页 > 解决方案 > 无法在反应打字稿中将函数作为上下文值传递

问题描述

这可能是一个菜鸟错误。但是我不能在 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

如果有人可以帮助我,那将非常有帮助。提前致谢。

标签: reactjsreact-contextreact-typescript

解决方案


对不起,就像我说的,那是一个菜鸟的错误。就像@Brian Thompson 说我必须将它作为对象而不是对象传递。


推荐阅读