window.addEventListener(' load',...无法在Safari上触发吗? [英] window.addEventListener('load',... not firing on Safari?

查看:68
本文介绍了window.addEventListener(' load',...无法在Safari上触发吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

加载后,我需要重定向页面并从URL获取参数.我可以通过单击按钮来完成.

但是我想要自动重定向页面(无用户输入).我正在使用 window.addEventListener('load',()=> handleClick()),它在Chrome上运行良好.但是在Safari(台式机和移动版)上,它并不总是会触发(仅有时会触发-并非总是).

我可以通过在处理程序中添加 alert('Beginning'); 来看到这一点-在Chrome上,页面加载后会自动触发,但在Safari上不会自动触发.

我该如何解决?

谢谢!

  const handleClick =异步(事件)=>{alert('Beginning');//用于调试const stripe =等待stripePromise;const {error} =等待stripe.redirectToCheckout({参数});}如果(typeof window!==`undefined`){const param = new URLSearchParams(window.location.search).get('param');}const Page =()=>{如果(typeof window!==`undefined`){window.addEventListener('load',()=> handleClick())}返回 (<节>< button role =链接"onClick = {handleClick}>//仅用于后备按</button></section>);};导出默认页面; 

解决方案

load 事件可能不是很可靠,因为您的组件可能要等到DOM加载后才被挂载..相反,您可以使用React组件的生命周期方法来将组件安装到页面时响应.例如:

 功能Component(){useEffect(()=> alert(1),[]);返回 (< h1>你好世界!</h1>);} 

您可以在文档中找到有关效果挂钩的更多信息.将其与空数组配合使用可使它像 componentDidMount() 用于类组件.

I need redirect page after it load and get param from URL. I can do by button click.

But I want redirect page automatic (without user input). I am use window.addEventListener('load', () => handleClick()) and it work well on Chrome. But on Safari (desktop and mobile) it not always fire (only sometimes it fire - not always).

I can see this by add alert('Beginning'); in handler - on Chrome this fire automatic after page load, but not on Safari.

How I can solve this?

Thanks!

const handleClick = async (event) => {

  alert('Beginning'); //For debugging


  const stripe = await stripePromise;
  const { error } = await stripe.redirectToCheckout({
    param,
  });
}

if (typeof window !== `undefined`) {
const param = new URLSearchParams(window.location.search).get('param');
}

const Page = () => {

  if (typeof window !== `undefined`) {
  window.addEventListener('load', () => handleClick())
  }

  return (
    <section >

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

    </section>
  );
};

export default Page;

解决方案

The load event probably wouldn't be very reliable, since your component probably wouldn't be mounted until after the DOM is loaded. Instead, you can use the lifecycle methods of React component to respond when your component is mounted to the page. For example:

function Component() {
  useEffect(() => alert(1), []);

  return (
    <h1>hello world!</h1>
  );
}

You can find more information about the Effect hook in the documentation. Using it with an empty array makes it work like componentDidMount() for class components.

这篇关于window.addEventListener(&amp;#39; load&amp;#39;,...无法在Safari上触发吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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