英文:
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.
<Route exact path="/employeedetails" element={<EmployeeDetails />} />
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
-
遇到过同样的问题。以下是一些解决方案,但据我所知,没有完美的方法来阻止刷新。
- 阻止 F5 键的按下
const blockRefresh = (e) => { if ((e.which || e.keyCode) == 116) e.preventDefault(); } window.addEventListener("keydown", blockRefresh);
如果这不能完美地阻止F5,请检查keyCode。
-
设置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.
- block F5 keyCode
const blockRefresh = (e) => {
if ((e.which || e.keyCode) == 116) e.preventDefault();
}
window.addEventListener("keydown", blockRefresh);
It will perfectly block the F5, if not, check the keyCode.
- set Beforeunload eventhandler
const blockRefresh = (e) => {
return "block Refresh"
}
window.addEventListener("beforeunload", 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("beforeunload", onBeforeUnload);
You can know more about that event click here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论