[英]How to detect/handle back button press in React?
我正在尝试检测用户按下后退按钮。 我有一个每次都记录 POP 的组件,即使用户没有按下后退按钮也是如此。 我只想在用户从另一个屏幕导航到组件时运行此代码。 我该怎么做呢?
const history = useHistory();
useEffect(() => {
console.log(history.action)
if (history.action == 'POP') {
// process
}, [data])
我不太确定您要在这里完成什么,但我认为您可以使用 useEffect 中的return
来检查用户何时返回。 return
在组件卸载时运行。
const history = useHistory();
useEffect(() => {
console.log(history.action)
if (history.action == 'POP') {
return function cleanup() {console.log("User pressed back")};
}, [data])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.