[英]How to detect/handle back button press in React?
I am trying to detect a user pressing the back button.我正在尝试检测用户按下后退按钮。 I have a component that logs POP every time, even when the user did not press back button.我有一个每次都记录 POP 的组件,即使用户没有按下后退按钮也是如此。 I want to run this code only when the user navigated to the component from another screen.我只想在用户从另一个屏幕导航到组件时运行此代码。 How do I do this?我该怎么做呢?
const history = useHistory();
useEffect(() => {
console.log(history.action)
if (history.action == 'POP') {
// process
}, [data])
I am not quite sure what you're trying to accomplish here but I think you could use the return
in useEffect to check when the user goes back.我不太确定您要在这里完成什么,但我认为您可以使用 useEffect 中的return
来检查用户何时返回。 return
runs when the component is unmounted. 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.