【问题标题】:Stripe reactjs - could not find elements contextStripe reactjs - 找不到元素上下文
【发布时间】:2021-01-14 10:37:19
【问题描述】:

我正在开发一个 ReactJS 项目,我想在其中集成条带以允许用户更新他们的订阅付款信息。

我正在关注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>
    )
}

但是,尽管感觉我已经按照文档进行操作,但在页面加载后立即收到以下错误:

错误:找不到元素上下文;你需要包装的部分 您在提供程序中调用 useStripe() 的应用

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

【问题讨论】:

    标签: reactjs stripe-payments


    【解决方案1】:

    除非您已经拥有正确的条带上下文,否则您不能调用 useElements

    这意味着您在此处显示的整个组件应该由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
    };
    

    【讨论】:

    • 我应该有return (&lt;Elements&gt;...Code from my component JSX from question&lt;/Elements&gt;,因为我已经尝试过了,但我仍然遇到同样的错误
    • 啊我想我明白你的意思了,它没有包裹在特定组件中,它包裹在应用程序返回而不是单个组件返回
    • 看起来它现在可以工作了。感谢您的帮助。必须将 &lt;Elements&gt; 标签包裹在 App.js 中的内容周围,而我只在我想要支付表单的组件中这样做。
    • 我在尝试从 react-stripe-elements 迁移时遇到了这个错误。我错误地从那个已弃用的包中导入了Elements,而不是react-stripe-js
    【解决方案2】:

    只需将你的组件放入一个Parent Component中,它被包裹在Elements Tag中:

    import React from "react";
    import {Elements} from '@stripe/react-stripe-js';
    import {loadStripe} from '@stripe/stripe-js';
    import ChildComponent from './ChildComponent'
    
    const ParentComponent= () => (
      <Elements stripe={stripePromise}>
        <ChildComponent />
      </Elements>
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多