Next.js: document is not defined

后端 未结 6 1698
一个人的身影
一个人的身影 2021-02-07 15:22

I am trying to create a payment form where people can pay but I keep getting this error.

document is not defined

I\'m using Next.js. Ple

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 16:03

    I think, in server rendering mode, the document is undefined. You should be able to use it inside class lifecycle methods or useEffect

    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 (
            


    Powered by Stripe

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

提交回复
热议问题