为什么会出现“ useContext不是函数”或“未定义上下文”的信息?

时间:2019-07-03 13:42:12

标签: reactjs

我正在尝试在无状态组件中使用上下文。我更新了对v16.8.0的反应,并添加了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;

2 个答案:

答案 0 :(得分:1)

const { useContext } = React

useContext被导出为React的方法属性

答案 1 :(得分:0)

您需要像这样导入useContext

import { useContext } from 'react';