简体   繁体   English

在反应中加载页面时自动打开新选项卡

[英]Auto open new tab when page is loaded in react

I have a requirement to be implemented where- when the form is loaded, basis one of the attribute which contains a url link - a new browser tab should be auto opened with that url when form is loaded.我有一个要求在何处实现 - 当加载表单时,基于包含 url 链接的属性之一 - 加载表单时应使用该 url 自动打开一个新的浏览器选项卡。

So i checked few stakc overflow links and found one solution Maintaining href "open in new tab" with an onClick handler in React所以我检查了几个 stakc 溢出链接并找到了一个解决方案Maintaining href "open in new tab" with an onClick handler in React

      const openInNewTab = (url) => {
        const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
        if (newWindow) newWindow.opener = null
      }


       return (
            <ul>
            {dataset.map((x, id) => (
                <li 
                key={id}
                >
                    <b>{x.split('~')[0]}</b>&ensp;-&ensp;{checkString(x.split('~')[1])}
                    {x.split('~')[0]==='PAGE_URL'  ?  
                        openInNewTab(x.split('~')[1])
                    :
                    <></>
                }
                </li>
               
            ))}
            </ul>
        );

So with above code, when my form is loaded, it immediately loads new tab on broswer as expected but the issue here is whenever i try to type in other form questions or click on any button like radio button on that form, everytime it is opening new tab which i don't want.因此,使用上面的代码,当我的表单加载时,它会立即按预期在浏览器上加载新选项卡,但这里的问题是每当我尝试输入其他表单问题或单击该表单上的任何按钮(如单选按钮)时,每次它打开时我不想要的新标签。 How do i prevent multiple times auto pop up of new tab or is there any other solution?如何防止多次自动弹出新标签页或是否有其他解决方案? Please help with solution or alternatives.请帮助解决方案或替代方案。

I mentioned whever i tried in above我在上面提到过我尝试过的任何地方

You can call the openInNewTab function from a useEffect hook.您可以从 useEffect 挂钩调用openInNewTab function。 The reason a new tab is opened when ever you type in something in the input field is because react is re-rendering that component due to state changes.当您在输入字段中输入内容时会打开一个新选项卡的原因是由于 state 更改,React 正在重新渲染该组件。 Since you want this function to be called only once, you can move the logic of calling this function to a useEffect hook.由于你希望这个 function 只被调用一次,你可以将调用这个 function 的逻辑移动到一个 useEffect hook 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM