簡體   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