【问题标题】:Can't pass function as Context Values in react typescript无法在反应打字稿中将函数作为上下文值传递
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 也许一个代码示例会有所帮助?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 2020-12-19
  • 2023-03-29
相关资源
最近更新 更多