【问题标题】:Stripe not initialized条带未初始化
【发布时间】:2021-02-07 12:31:53
【问题描述】:

我决定将 nextjs 与 stripe 一起使用并这样做,但我收到错误 Error: Please pass a valid Stripe object to StripeProvider。您可以通过使用可发布密钥调用“Stripe(...)”来获取 Stripe 对象。 我正在传递一个条纹对象,但奇怪的是它没有通过,即使尝试在 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>
    </>
  )
}

【问题讨论】:

    标签: reactjs stripe-payments next.js


    【解决方案1】:

    您应该使用来自@stripe/stripe-jsloadStripe 帮助程序和来自@stripe/react-stripe-jsElements 提供程序,而不是尝试像这样围绕Stripe.js 加载构建您的组件。这将在初始化的同时为您异步加载 Stripe.js。

    Docs

    例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      相关资源
      最近更新 更多