如何在 React 组件之外加载 Stripe Promise?

How to load Stripe promise outside of React component?

我在 React 中做出 Stripe 承诺,他们的文档说要在组件外部加载承诺,如下所示:

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

// Make sure to call `loadStripe` outside of a component’s render to avoid
// recreating the `Stripe` object on every render.
const stripePromise = loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

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

我的问题是我从 API 获取 public 密钥并将其存储在 redux 中(我们连接到几个不同的公司)。在组件中加载它会导致重新渲染:

import React from "react";
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import { useSelector } from "react-redux";
import ExpressCheckout from "./ExpressCheckout";

const ExpressContainer = () => {
  const stripe_PK = useSelector(
    (state) => state.company.presenter.data_stripe_pk
  );
  const stripePromise = loadStripe(stripe_PK);
  return (
    <Elements stripe={stripePromise}>
      <ExpressCheckout />
    </Elements>
  );
};

export default ExpressContainer;

我尝试使用 getState() 在组件之前加载 redux 状态,但它返回空白。

您需要推迟调用 loadStripe,直到您从选择器中获得 PK 的有效值。

当您 provide null<Elements />stripe 属性时,它会延迟初始化。您可以将 一次 从空值更改为解析为 Stripe 对象的承诺,但不允许更改 stripe 属性。

stripe

required Stripe | null | Promise<Stripe | null>

A Stripe object or a Promise resolving to a Stripe object. The easiest way to initialize a Stripe object is with the Stripe.js wrapper module. After this prop has been set, it can not be changed.

You can also pass in null or a Promise resolving to null if you’re performing an initial server-side render or when generating a static site.

我在这里设置了一个示例,其中 setTimeout 模拟密钥的延迟加载,然后 useEffect 触发调用 loadStripehttps://codesandbox.io/s/react-stripe-js-delayed-key-effect-boxmz

这不是实现此目的的唯一方法,但它说明了这个想法。