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

时间:2020-04-19 04:45:03

标签: reactjs react-hooks stripe-payments

在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>
  )
}

1 个答案:

答案 0 :(得分:1)

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

Only call hooks from react functions

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

Only call hooks at the top level

请勿在循环,条件或嵌套函数内调用Hook。 相反,请始终在您的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?
  };


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