Stripe:在 nextjs 中找不到 Elements 上下文错误

Aha*_*mii 4 stripe-payments reactjs next.js

我在 nextjs 12 中使用 stripe 下面的包

import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
Run Code Online (Sandbox Code Playgroud)

它在开发模式下运行良好,但在生产构建时会抛出此错误

Error: Could not find Elements context; You need to wrap the part of your app that calls useStripe() in an <Elements> provider.
Run Code Online (Sandbox Code Playgroud)

我使用 Elements 作为父容器,并使用 Elements 内的 Checkoutform 作为子容器

import React from 'react'
import { useAppContext } from '@/context/AppContext';
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import Checkoutform from './Checkoutform';
import AppLoader from '@/components/common/Loader';

const Payment = () => {
    const { state } = useAppContext();
    const { user, planType } = state;
    const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_KEY);
    const options = {
        clientSecret: planType.orderData.client_secret,
        appearance: {
            theme: 'stripe',
        }
    };

    return (
        options.clientSecret && options.clientSecret.length > 0 ? (
            <Elements stripe={stripePromise} options={options} >
                <Checkoutform userData={user} planType={planType} />
            </Elements >
        ) : (
            <AppLoader />
        )
    )
}


export default Payment
Run Code Online (Sandbox Code Playgroud)

结账表格.js

import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
Run Code Online (Sandbox Code Playgroud)

请帮助我我做错了什么或者我必须为生产构建添加什么

Har*_*per 6

如果您使用 checkoutform.js 作为组件,那么乔纳森·斯蒂尔(Jonathan Steele)是对的,然后确保将其保存在组件文件夹中,该文件夹应该位于页面文件夹之外。因为如果它位于页面文件夹内,那么在构建过程中,nextjs 会尝试通过将其视为页面来预渲染它,这会给您带来此错误


归档时间:

查看次数:

1451 次

最近记录:

2 年,2 月 前