簡體   English   中英

React hooks - 在 useEffect 內設置超時但能夠從鼠標事件中清除它?

[英]React hooks - Set a timeout inside useEffect but be able to clear it from a mouse event?

這是一個經典的菜單案例,單擊按鈕打開,如果沒有活動則在 5 秒內隱藏。 我們有 2 個狀態變量。 open 和 active,對應兩種不同的狀態 = menu 是 open 和 active(正在使用)。 我使用按鈕單擊設置了 open 變量,然后實際上我開始了 5 秒超時。 現在,如果用戶將鼠標懸停在菜單上,我將 active 屬性設置為 true 並嘗試清除超時。 但這行不通。 意思是,超時變量在應該清除它的代碼中始終為空。

這里有一些代碼可以幫助您理解:

let [open, openMenu] = useState(false)
let [active, activateMenu] = useState(false)

let timer = null;
useEffect(() => {
    if(open && !active) {
        timer = setTimeout(() => setOpen(false), 5000)
    }

    if(open && active) {
        if(timer) {
            clearTimeout(timer)
        }
    }
}, [open, active])

// Triggered via the UI on a button click
openMenuhandler() {
    setOpen(true)
}

// Triggered via the UI on mouseenter
// identifies that the menu is being used, when mouse is over it
setMenuActive() {
    activateMenu(true)
}

// Triggered via the UI on mouseleave
setMenuInActive() {
    activateMenu(false)
}

// other code here on

現在超時永遠不會被清除。 無論如何,菜單都會在 5 秒內隱藏。 還有另一種方法嗎? 我什至嘗試將 clearTimeout 移動到 mouseLeave,但即使如此,計時器還是空的。 如何解決這個問題? 請幫忙。

每當您的組件重新渲染時, timer變量將被重新聲明為初始值null 因此,當useEffect鈎子在其任何依賴項更改時執行時, timer變量為null

您可以通過確保timer變量的值在組件的重新渲染中保持不變來解決該問題。 要在重新渲染時保留該值,請使用useRef鈎子保存setTimeout的 id 或將其保存在狀態中,即useState鈎子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM