gpt4 book ai didi

reactjs - 为什么我得到 “useContext is not a function”或 “context is not defined”?

转载 作者:行者123 更新时间:2023-12-03 14:01:16 26 4
gpt4 key购买 nike

我试图在我的无状态组件中使用上下文。我更新了对v16.8.0的 react ,并添加了useContext,但是,我不断遇到这两个错误,不知道该怎么办。这是我的代码:

import React, { useState } from "react";
import axios from "axios";
import { LanguageContext } from "./languageContext";
import { useContext } from "react";

function StripeButton() {
const context = useContext(LanguageContext);
const stripe = Stripe("pk_live_5PjwBk9dSdW7htTKHQ3HKrTd");

const [error, setError] = useState();

const handleClick = () => {
stripe
.redirectToCheckout({
...
});
};

return (
<div>
<button
id="UrgentCheckedButtonYES"
className="btn-primary"
onClick={handleClick}
>
{this.context.main.name}
<br />
</button>
<div>{error}</div>
</div>
);
}

export default StripeButton;
StripeButton.contextType = LanguageContext;

最佳答案

您需要像这样导入useContext:

import { useContext } from 'react';

关于reactjs - 为什么我得到 “useContext is not a function”或 “context is not defined”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56871537/

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