URLSearchParam 后如何调用函数? [英] How to call function after URLSearchParam?

查看:29
本文介绍了URLSearchParam 后如何调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在加载后重定向页面并从 URL 获取参数.我可以通过单击按钮来完成.但是如何在页面从 URL 获取参数后自动进行页面重定向(无需用户输入)?

I need redirect page after it load and get param from URL. I can do by button click. But how I can make page redirect automatic after page have get param from URL (without user input)?

谢谢!

const handleClick = async (event) => {
  const stripe = await stripePromise;
  const { error } = await stripe.redirectToCheckout({
    param,
  });
}

const param = new URLSearchParams(window.location.search).get('param');


const Page = () => {
  React.useEffect(() => {
    window.scrollTo(0, 0);
  }, []);
  return (
    <section >

      <button role="link" onClick={handleClick}>
      Press
    </button>

    </section>
  );
};

export default Page;

推荐答案

您将需要在 init/load 处理程序中解析这些查询参数.你可以看到一个例子 这里.请注意,DOMContentLoaded 上的事件侦听器会启动一切.可以在此处查看此操作的示例.

You're going to want to parse those query parameters in the init/load handler. You can see an example of this here. Note that the event listener on DOMContentLoaded kicks everything off. An example of this in action can be seen here.

我注意到您的代码直接在 Checkout 重定向中使用了 param.如果 param 是一个结帐会话,您应该按需生成它们,而不是通过电子邮件链接等发送它们,因为它们是短暂的.在上面的示例中,code 参数被读取并用于通过 fetch 生成新的结帐会话,然后用于重定向.

I noticed that your code uses param in the Checkout redirect directly. If param is a checkout session that you should be generating these on demand, not sending them in emailed links etc, as they are short-lived. In the example above, the code param is read and use to generate a new checkout session via a fetch and then that is used for the redirect.

这篇关于URLSearchParam 后如何调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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