reactjs - 条带未初始化
问题描述
我决定将 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>
</>
)
}
解决方案
与其尝试像这样围绕 Stripe.js 加载构建组件,您应该将loadStripe
helper from@stripe/stripe-js
与Elements
提供程序 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>
);
};
推荐阅读
- python - 如何从python中的数组中删除重复的组合
- python - 测试不同人群的现有模型?
- algorithm - 二维叉积定义
- c# - 以编程方式创建 Google Firebase 存储桶 Unity / C#?
- javascript - 如何检查某个字符是否在字符串中多次存在?
- python - 如何在 Python 中仅使用“for 循环”编写牛顿平方根方法?无条件
- reactjs - 当您点击刷新时,在 IIS 上反应路由 404 错误
- python - WTForms TimeField 默认值
- javascript - 创建两个 action 和两个 reducer 来为两个不同的组件获取相同的数据是否可以接受?
- angular - 为什么常规模块导入路由模块而不是反向