首页 > 解决方案 > 条带未初始化

问题描述

我决定将 nextjs 与 Stripe 一起使用并这样做,但我收到错误错误:请将有效的 Stripe 对象传递给 StripeProvider。您可以通过使用可发布密钥调用“Stripe(...)”来获取 Stripe 对象。我正在传递一个条纹对象,但奇怪的是它没有通过,即使在尝试 console.log in next.js 时它也没有显示在控制台中。那我做错了什么?谢谢

function MyApp({ Component, pageProps }) {
  const [stripe, setStripe] = useState({ stripe: null });
  useEffect(() => {
    console.log("djdsjdjsd");
    if (window.Stripe) {
      setStripe({ stripe: window.Stripe('pk_test') });
    } else {
      document.querySelector('#stripe-js').addEventListener('load', () => {
        // Create Stripe instance once Stripe.js loads
        setStripe({ stripe: window.Stripe('pk_test') });
      });
    }
  }, []);
  return (
    <>
      <Head>
        <title>My page title</title>
        <meta property="og:title" content="My page title" key="title" />
        <script async src="https://js.stripe.com/v3/"></script>
      </Head>
      <StripeProvider stripe={stripe}>
        <Component {...pageProps} />
      </StripeProvider>
    </>
  )
}

标签: reactjsstripe-paymentsnext.js

解决方案


与其尝试像这样围绕 Stripe.js 加载构建组件,您应该将loadStripehelper from@stripe/stripe-jsElements提供程序 from一起使用@stripe/react-stripe-js。这将在初始化的同时为您异步加载 Stripe.js。

文档

例子:

import {Elements} from '@stripe/react-stripe-js';
import {loadStripe} from '@stripe/stripe-js';

const stripePromise = loadStripe('pk_test_123');

const App = () => {
  return (
    <Elements stripe={stripePromise}>
      <PaymentComponentWithCardElementEtc />
    </Elements>
  );
};

推荐阅读