gpt4 book ai didi

javascript - react : TypeError: _useContext is undefined

转载 作者:行者123 更新时间:2023-12-02 23:11:50 25 4
gpt4 key购买 nike

我正在尝试 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 和依赖项都是最新的。

最佳答案

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

评论因 stackoverflow 被删除。

关于javascript - react : TypeError: _useContext is undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57319350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com