Stripe useStripe()与useElements()返回空值,支付组件无法渲染
Stripe支付表单异常:useStripe()/useElements()返回null,CardElement无法渲染
我在开发Stripe支付表单时遇到以下问题:
useStripe()和useElements()Hook始终返回nullCardElement组件完全无法渲染
我猜测问题出在stripePromise没有正常解析,但找不到具体原因和解决办法。以下是相关代码:
Stripe容器组件
interface SubPlanPaymentPageProps { subscription: Subscription | null; } const PUBLIC_TEST_KEY = 'XXXXXXXXX'; const stripePromise = loadStripe(PUBLIC_TEST_KEY); const SubPlanPaymentPage: React.FC<SubPlanPaymentPageProps> = ({subscription}) => { const [clientSecret, setClientSecret] = useState(''); const options = { clientSecret, }; useEffect(() => { fetch("http://localhost:3000/payment/create-payment-intent", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({subscription}), }) .then((res) => res.json()) .then((data) => setClientSecret(data.clientSecret)); }, []); return ( <div> {clientSecret && ( <Elements stripe={stripePromise} options={options}> <StripePaymentForm /> <button onClick={()=> console.log(stripePromise)}>secret</button> // 点击后控制台输出:Promise {<pending>} </Elements> ) } </div> ); };
支付表单组件
export default function StripePaymentForm() { const stripe = useStripe(); const elements = useElements(); const handleSubcribe = async (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); if (!stripe || !elements) { // 这里控制台输出:stripe: null, elements: null console.log('stripe:', stripe, 'elements:', elements); return; } console.log('stripe:', stripe, 'elements:', elements); const cardElement = elements.getElement(CardElement); if (!cardElement) { return; } const { paymentMethod, error } = await stripe.createPaymentMethod({ type: 'card', card: cardElement, billing_details: { name: 'John Doe', }, }); if (error) { console.error('error:', error); } else { console.log(paymentMethod); } }; return ( <div className='payment-form-container'> <form onSubmit={handleSubcribe}> <div className='row'> <CardElement /> // 这个组件没有渲染 </div> <button>Subscribe</button> </form> </div> ); }
已尝试的解决方案
我试过通过useEffect初始化Stripe实例,但问题依然存在:
useEffect(()=> { const initStripe = async () => { const stripeInstance = await loadStripe('your-publishable-key'); setStripePromise(stripeInstance) } initStripe(); },[])
内容的提问来源于stack exchange,提问作者JerryC
相关产品推荐
相关产品推荐

