反应:TypeError:_useContext未定义

时间:2019-08-02 02:59:19

标签: javascript reactjs typescript

我正在尝试TypeScript和React。我有一个功能组件(下面的代码),该组件应该使用useContext来使用上下文,但是它向我显示了这个奇怪的错误,我找不到解决方法。

如果我不使用TS,而是使用JSX,它就可以正常工作。

编辑:屏幕截图> enter image description here

代码:

AppProvider.tsx

import React, { useState, useEffect } from "react";

// Application's context (for general application-wide usage)
const AppContext: any = React.createContext(null);

// this will be used below in the componet we will export
export const AppContextProvider = AppContext.Provider;

export const AppProvider: React.FC = (props: any) => {
  const [appName, setAppName] = useState("Blood Donation");
  const [appUser, setAppUser]: any = useState(null);
  const [appInfoBusy, setAppInfoBusy] = useState(false); // working to get or set data

  useEffect(() => {
    getAppInfo();
  }, []);

  const getAppInfo = () => {
    setTimeout(() => {
      setAppName("Test");
      setAppUser({
        name: "Admin",
        email: "test@test.com",
        role_id: 100
      });
    }, 3000);
  };

  return (
    <AppContextProvider
      value={{
        appName: appName,
        appInfoBusy: appInfoBusy,
        appUser: appUser
      }}
    >
      {props.children}
    </AppContextProvider>
  );
};

消费者:Login.tsx

import React, { useState, useEffect, useContext } from "react";
import {
  Button,
  Card,
  Elevation,
  FormGroup,
  InputGroup,
  Drawer,
  Classes,
  H4,
  Callout,
  H5
} from "@blueprintjs/core";
//@ts-ignore
import ReCAPTCHA from "react-google-recaptcha";

import logo from "../../assets/images/logo.png";
import "../../scss/Login.scss";
import { RecaptchaKey } from "../../shared/Info";
import { AppContextProvider } from "../../shared/context/AppProvider";

const Login: React.FC = props => {
  const [email, setEmail]: React.ComponentState = useState();
  const [password, setPassword]: any = useState();
  const [isOpen, setIsOpen]: any = useState();
  const [resetEmail, setResetEmail]: any = useState();
  const [emailSent, setEmailSent]: any = useState();
  const [captchaOk, setCaptchaOk]: any = useState(false);
  const [working, setWorking]: any = useState(false);

  // context
  const { appName, appUser, appInfoBusy } = useContext(AppContextProvider);

  /**
   * Handles lifecycle hooks
   */
  useEffect(() => {
    // when component is mounted
  }, []);

  /**
   * Handles Captcha change
   * @param value
   */
  const recaptchaChange = (value: any) => {
    setCaptchaOk(value ? true : false);
  };

  const handleRecoverySubmit = () => {
    setWorking(true);
    setTimeout(() => {
      setEmailSent(true);
      setWorking(false);
    }, 3000);
  };

  return (
    <div id="loginPage">
      ... removed for brevity ...
    </div>
  );
};

export default Login;

非常感谢任何帮助。 React和依赖项都是最新的。

1 个答案:

答案 0 :(得分:-1)

我在useContext()中使用上下文提供程序而不是上下文本身,我应该使用useContext(AppContext)

注释已删除,因为堆栈溢出。