我试图创建一个付款表单,人们可以付款,但我一直收到这个错误.

文档未定义

我在用Next.js.请看下面我的代码:

import React from "react";
import {Elements, StripeProvider} from 'react-stripe-elements';
import CheckoutForm from '../../components/Payment/CheckoutForm';
import { useRouter } from 'next/router';


var stripe_load = () => {
    var aScript = document.createElement('script');
    aScript.type = 'text/javascript';
    aScript.src = " https://js.stripe.com/v3/";

    document.head.appendChild(aScript);
    aScript.onload = () => {

    };
};

function Payment({host}) {
    const key = host.includes('localhost') ? 'test' : 't';

    stripe_load();

    const router = useRouter();

    return (
        <div className="Payment Main">
            <StripeProvider apiKey={key}>
                <Elements>
                    <CheckoutForm planid={router.query.id}/>
                </Elements>
            </StripeProvider>
            <br/>
            <br/>
            <p>Powered by Stripe</p>
        </div>
    );
};


Payment.getInitialProps = async ctx => {
    return { host: ctx.req.headers.host }
};

export default Payment

推荐答案

我认为,在服务器呈现模式下,文档是未定义的.

import React, {useEffect} from "react";
import {Elements, StripeProvider} from 'react-stripe-elements';
import CheckoutForm from '../../components/Payment/CheckoutForm';
import { useRouter } from 'next/router';


var stripe_load = () => {
    var aScript = document.createElement('script');
    aScript.type = 'text/javascript';
    aScript.src = " https://js.stripe.com/v3/";

    document.head.appendChild(aScript);
    aScript.onload = () => {

    };
};

function Payment({host}) {
    const key = host.includes('localhost') ? 'test' : 't';

    useEffect(() => {
      var aScript = document.createElement('script');
       aScript.type = 'text/javascript';
       aScript.src = " https://js.stripe.com/v3/";

       document.head.appendChild(aScript);
       aScript.onload = () => {

       };
    }, [])
    //stripe_load();

    const router = useRouter();

    return (
        <div className="Payment Main">
            <StripeProvider apiKey={key}>
                <Elements>
                    <CheckoutForm planid={router.query.id}/>
                </Elements>
            </StripeProvider>
            <br/>
            <br/>
            <p>Powered by Stripe</p>
        </div>
    );
};


Payment.getInitialProps = async ctx => {
    return { host: ctx.req.headers.host }
};

export default Payment

Reactjs相关问答推荐

useReducer和带有回调的useState之间是否有实际区别?

如何通过TEK查询将对象传递到Express后台

Next.js-图像组件加载问题

捕获表单数据时的Reactjs问题

状态更改时的rtk查询触发器

如何在中间件中获取 nextAuth 会话

在迭代状态时无法读取未定义的属性(读取 map )

组件安装后调用自定义钩子

无法通过react 路由中的链接传递信息

如何在不使用 Axios 的情况下将图像文件从 React.js 发送到 Spring Boot Rest API?

Primereact 的日历组件在每个月 12 日之后使用非唯一键生成

添加新行时自动打开可扩展表格(Antd 表格,ReactJS)

下一次导出:未捕获的语法错误:标识符注册表已被声明

React - 仅在变量为真时显示项目

刷新页面时状态改变问题

使用输入类型文本对 useState 和日期做出react

如何解决在 react.js 中找不到模块错误

getAttribute 函数并不总是检索属性值

未捕获的错误:操作必须是使用 redux/toolkit 的普通对象

React LinkProps 的含义