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. 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. return
runs when the component is unmounted.
const history = useHistory();
useEffect(() => {
console.log(history.action)
if (history.action == 'POP') {
return function cleanup() {console.log("User pressed back")};
}, [data])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.