gpt4 book ai didi

reactjs - Stripe reactjs - 找不到元素上下文

转载 作者:行者123 更新时间:2023-12-04 14:37:06 29 4
gpt4 key购买 nike

我正在研究一个 ReactJS 项目,我想在其中集成 Stripe 以允许用户更新他们的订阅付款信息。
我正在关注 https://stripe.com/docs/stripe-js/react 的指南但我遇到了一个问题。
以下是我目前拥有的代码

const stripe = useStripe();
const elements = useElements();

const errorDialogueCleared = () => {
setAPIResult(null);
}

const stripePromise = loadStripe('my_test_key');

const baseStripeElementOptions = {
style: {
base: {
fontFamily: 'Oxanium',
fontSize: '16px',
color: '#000000',
'::placeholder': {
color: '#000000',
},
},
invalid: {
color: '#9e2146',
},
}
}

const handleSubmit = async (event) => {
// Block native form submission.
event.preventDefault();

if (!stripe || !elements) {
// Stripe.js has not loaded yet. Make sure to disable
// form submission until Stripe.js has loaded.
return;
}

// Get a reference to a mounted CardElement. Elements knows how
// to find your CardElement because there can only ever be one of
// each type of element.
const cardElement = elements.getElement(CardElement);

// Use your card Element with other Stripe.js APIs
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
});

if (error) {
console.log('[error]', error);
} else {
console.log('[PaymentMethod]', paymentMethod);
}
};

return (

<div className='container-fluid'>

<div className="mainContentNoSidebar">

<TopNavBar displayTimePeriodButton={false} title='Update Account Information' />

<BreadcrumbNav menu_items={breadcrumbNav} />

<div className='contentWrapper'>

<div className='container'>
<h1>Update Account Information</h1>
<form onSubmit={handleSubmit} style={{width: '50%', marginLeft: 'auto', marginRight: 'auto'}}>
<Elements stripe={stripePromise}>
<CardElement options={baseStripeElementOptions} />
</Elements>

<button className='btn btn-primary'>Submit Payment Details</button>
</form>
</div>



</div>
</div>

<ErrorDialogue dialogClosed={errorDialogueCleared} api_result={currentError} />
</div>
)
}
但是,尽管感觉我已经按照文档进行了操作,但在页面加载后立即出现以下错误:

Error: Could not find Elements context; You need to wrap the part ofyour app that calls useStripe() in an provider


我的 CardElement包裹在 Elements 中组件,所以我不确定为什么我会看到这个错误。

最佳答案

您不能调用 useElements除非您已经拥有正确的 strip 上下文。
这意味着您在此处显示的整个组件应该由 Elements 包裹。而不仅仅是 CardElement .
它应该是这样的:

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

const stripePromise = loadStripe('STRIPE_PUBLISHABLE_API_KEY');

const Wrapper = (props) => (
<Elements stripe={stripePromise}>
<MyComponent {...props} />
</Elements>
);

const MyComponent = (props) => {
const stripe = useStripe();
const elements = useElements();

// rest of the component
};

关于reactjs - Stripe reactjs - 找不到元素上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64109065/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com