避免在用户刷新或按下F5按钮时重新加载页面。

huangapple go评论66阅读模式
英文:

Avoid realoading a page when user refresh or press F5 button

问题

我有一个带表格的React页面。表格中有一列超链接,当我点击特定的超链接时,会打开一个新页面,显示有关所点击的超链接或行的详细信息。

<Route exact path="/employeedetails" element={<EmployeeDetails />} />

我想要避免在用户刷新或按下F5时重新加载"Employee Details"页面。或者,我如何捕获刷新事件并调用React组件。

英文:

I have react page with table. Table has a column with hyperlink when I click on a particular hyperlink new page open with details about the clicked hyperlink or row.

&lt;Route exact path=&quot;/employeedetails&quot; element={&lt;EmployeeDetails /&gt;} /&gt; 

I want to avoid reloading Employee Details page when user refresh or press F5. Or How can I capture a refresh event and call the React component.

答案1

得分: 2

  1. 遇到过同样的问题。以下是一些解决方案,但据我所知,没有完美的方法来阻止刷新。

    1. 阻止 F5 键的按下
    const blockRefresh = (e) => {
      if ((e.which || e.keyCode) == 116) e.preventDefault();
    }
    
    window.addEventListener("keydown", blockRefresh);
    

    如果这不能完美地阻止F5,请检查keyCode。

  2. 设置beforeunload事件处理程序

    const blockRefresh = (e) => {
      return "阻止刷新";
    }
    
    window.addEventListener("beforeunload", blockRefresh);
    

    但是,当您点击浏览器的刷新按钮时,如果有浏览历史记录,页面仍然会刷新。

英文:

I had experienced same problem. Here is the some of solutions but there is no perfect way to block the refreshing as I know.

  1. block F5 keyCode
const blockRefresh = (e) =&gt; {
  if ((e.which || e.keyCode) == 116) e.preventDefault();
}

window.addEventListener(&quot;keydown&quot;, blockRefresh);

It will perfectly block the F5, if not, check the keyCode.

  1. set Beforeunload eventhandler
const blockRefresh = (e) =&gt; {
  return &quot;block Refresh&quot;
}

window.addEventListener(&quot;beforeunload&quot;, blockRefresh);

But, when you click the browser refresh button, it will be refreshed if there are routing history.

答案2

得分: 2

你可以使用窗口的 beforeunload 事件:

function onBeforeUnload($event){

}
window.addEventListener("beforeunload", onBeforeUnload);

你可以在此链接中了解更多有关该事件的信息:点击这里

英文:

You can use the window beforeunload event:

function onBeforeUnload($event){

}
window.addEventListener(&quot;beforeunload&quot;, onBeforeUnload);

You can know more about that event click here

huangapple
  • 本文由 发表于 2023年7月10日 14:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651079.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定