等待在 nextjs 页面中加载贝宝脚本 [英] wait for loading paypal script in nextjs page

查看:46
本文介绍了等待在 nextjs 页面中加载贝宝脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码应该呈现贝宝按钮.

I have this code that is supposed to render the paypal buttons.

    <Head>
      <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script>
    </Head>

我在 componentDidMount 方法中加载贝宝按钮

I load the paypal buttons in the componentDidMount method

componentDidMount() {
    paypal
.Buttons({
  createOrder: (data, actions)=> {
    return actions.order.create({
      purchase_units: [{
          amount: {
            currency_code: "USD",
            value: amount,
          },
        }],
    });
  },
  onCancel: function(data){
    //console.log(data)

  },
  onError: function(err){
    console.log(err)
  }
})
.render("#paypal");
 }




<div id="paypal" className=""></div>

在第一页加载时,页面抛出一​​个错误,即未定义 paypal 我猜是因为在调用 componentDidMount 方法时脚本未完全加载.如何等到脚本加载后按钮才能正确呈现

on first page load the page throws an error that paypal is not defined i am guessing because the script is not loaded fully when the componentDidMount method is called. How can I wait until the script is loaded for the buttons to be rendered properly

推荐答案

const addPayPalScript = () => {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = `https://www.paypal.com/sdk/js?client-id=${process.env.PAYPAL_CLIENT_ID}`;
    // script.setAttribute("data-namespace", "paypal_sdk");

    script.async = true;
    script.onload = () => {
      setSdkReady(true);
    };
    document.body.appendChild(script);
  };

script.onload 将标记它已准备就绪.在 useState 中跟踪它

script.onload will flag that it is ready. Track it in useState

   const [sdkReady, setSdkReady] = useState(false);

然后在 useEffect 或 componentDidMount 中调用 addPayPalScript.我使用 useEffect

then call addPayPalScript inside useEffect or componentDidMount. I use useEffect

useEffect(() => {
dispatch(orderDetailRequestStart(paramsId));

  if (!window.paypal) {
    addPayPalScript();
  } else {
    // flags that it is ready
    setSdkReady(true);
  }

}, []);

这篇关于等待在 nextjs 页面中加载贝宝脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆