【问题标题】:Invalid hook call error occurs in Stripe + ReactStripe + React 出现无效的钩子调用错误
【发布时间】:2020-08-01 14:38:04
【问题描述】:

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

错误:

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

代码:

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

【问题讨论】:

标签: reactjs react-hooks stripe-payments


【解决方案1】:

React 钩子仅适用于函数式组件。

Only call hooks from react functions

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

Only call hooks at the top level

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

不能在handleStripe 回调中定义useStateuseElements

将逻辑转换/分解为一个小的功能组件。 将钩子移到主函数体中。

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

【讨论】:

  • 一旦我导出这个功能组件(以便从我的结帐页面使用它)我立即再次收到错误:无效的挂钩调用。 Hooks 只能在函数组件内部调用
  • @AugustoSamaméBarrientos 您好,如果您使用 您的 代码实现和调试详细信息打开一个新的 stackoverflow 问题(您可以参考此帖子/解决方案)会更有帮助。随意在这里放一个链接,有机会我可以看看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2021-04-15
  • 2021-03-30
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多