在Stripe + React中发生无效的挂钩调用错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Stripe + React中发生无效的挂钩调用错误相关的知识,希望对你有一定的参考价值。

[在Stripe + React中建立付款。我在官方文档中使用了该示例,但它不起作用。付款表格有效,但是提交结帐按钮时出现invalid hook call错误。

错误:

未捕获(承诺)错误:无效的挂钩调用。只能在函数组件的主体内部调用挂钩。

代码:

import React, { Component } from "react";
import {
  Elements,
  useStripe,
  useElements,
  CardElement,
} from "@stripe/react-stripe-js";
import { stripePromise } from "../../config/stripe";

handleStripe = async (event) => {
  const stripe = useStripe();
  const elements = useElements();

  event.preventDefault();
  console.log("event", event);
  const { error, paymentMethod } = await stripe.createPaymentMethod({
    type: "card",
    card: elements.getElement(CardElement),
  });
};

render() {
  return (
    <Elements stripe={stripePromise}>
      <CardElement />
        <button
          onClick={() => this.handleStripe()}
        >
          <span>
            Checkout
          </span>
        </button>
    </Elements>
  )
}
答案

反应挂钩仅在功能组件中起作用。

Only call hooks from react functions

它们不适用于基于类的组件。

Only call hooks at the top level

不要在循环,条件或嵌套函数内调用Hooks。相反,请始终在React函数的顶层使用挂钩。

不能在useState回调中定义useElementshandleStripe

将逻辑转换/分解为小的功能组件。将挂钩移出至主要功能主体。

import React from "react";
import {
  Elements,
  useStripe,
  useElements,
  CardElement,
} from "@stripe/react-stripe-js";
import { stripePromise } from "../../config/stripe";

const StripeComponent = props => {
  const stripe = useStripe();
  const elements = useElements();

  const handleStripe = async (event) => {
    event.preventDefault();
    console.log("event", event);
    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: "card",
      card: elements.getElement(CardElement),
    });
    // do something with error or paymentMethod?
  };

  render() {
    return (
      <Elements stripe={stripePromise}>
        <CardElement />
          <button
            onClick={handleStripe}
          >
            <span>
              Checkout
            </span>
          </button>
      </Elements>
    )
  }
}

以上是关于在Stripe + React中发生无效的挂钩调用错误的主要内容,如果未能解决你的问题,请参考以下文章

错误 无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用

× 错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。[ReactJS]

React Hooks:在验证时实例化状态挂钩错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用

最小示例中的无效挂钩调用错误[关闭]

React 17 - 添加 Evergreen UI 窗格会导致错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。 (React-hooks React-native)