繁体   English   中英

如何在 React 中检测/处理后退按钮按下?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM