使用 react-router 检测用户离开页面 [英] Detecting user leaving page with react-router
问题描述
我希望我的 ReactJS 应用程序在离开特定页面时通知用户.特别是提醒他/她执行操作的弹出消息:
I want my ReactJS app to notify a user when navigating away from a specific page. Specifically a popup message that reminds him/her to do an action:
更改已保存,但尚未发布.现在执行吗?"
"Changes are saved, but not published yet. Do that now?"
我应该在 react-router
上全局触发这个,还是可以在 react 页面/组件内完成?
Should i trigger this on react-router
globally, or is this something that can be done from within the react page / component?
我没有发现关于后者的任何信息,我宁愿避免第一个.当然,除非它是常态,但这让我想知道如何做这样的事情而不必向用户可以访问的每个其他可能的页面添加代码..
I havent found anything on the latter, and i'd rather avoid the first. Unless its the norm of course, but that makes me wonder how to do such a thing without having to add code to every other possible page the user can go to..
欢迎提供任何见解,谢谢!
Any insights welcome, thanks!
推荐答案
react-router
v4 引入了一种使用 Prompt
阻止导航的新方法.只需将其添加到您要阻止的组件中即可:
react-router
v4 introduces a new way to block navigation using Prompt
. Just add this to the component that you would like to block:
import { Prompt } from 'react-router'
const MyComponent = () => (
<>
<Prompt
when={shouldBlockNavigation}
message='You have unsaved changes, are you sure you want to leave?'
/>
{/* Component JSX */}
</>
)
这将阻止任何路由,但不会阻止页面刷新或关闭.要阻止它,您需要添加它(根据需要使用适当的 React 生命周期更新):
This will block any routing, but not page refresh or closing. To block that, you'll need to add this (updating as needed with the appropriate React lifecycle):
componentDidUpdate = () => {
if (shouldBlockNavigation) {
window.onbeforeunload = () => true
} else {
window.onbeforeunload = undefined
}
}
onbeforeunload 受到浏览器的各种支持.
onbeforeunload has various support by browsers.
这篇关于使用 react-router 检测用户离开页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!