首页 > 解决方案 > 无法使用 clearTimeout 停止 setTimeout 函数,因为由于某种原因值为 null

问题描述

在我的 react-native 应用程序中,我试图停止setTimeout使用clearTimeout. 我将 的实例保存setTimeout在全局变量中。

let timeoutId:any = null;

    const doOtp = ()=>{
        if(canSendOtp) {
            setCanSendOtp(false);

            timeoutId = setTimeout(() => { // it has here a numeric value
                showNotificationMessage("You can request OTP again")
                setCanSendOtp(true)
            }, SEND_OTP_TIME_CONSTRAINTS)

           // rest of doOtp logic
        }
        else {
            showNotificationMessage("Please wait " + (SEND_OTP_TIME_CONSTRAINTS / 1000) + " seconds before trying again")
        }
    }

然后,当我想使用 clearTimeout 停止 setTimeout 时,我看到的timeoutId值为null。我不明白为什么会这样。

const doLogin = () => {
issueToken(LOGIN_GRANT_TYPE, LOGIN_CLIENT_ID, LOGIN_CLIENT_SECRET, phoneNumber, otp)
    .then(res => { 
        
        console.log('timeoutId !== null' + timeoutId !== null)
        if(timeoutId !== null) { // value here is null - why?
            clearTimeout(timeoutId)
        }

        store().dispatch(setTokenValidity(res))
    })
    .catch(err => {
        showNotificationMessage('Error, something went wrong check logs.')
        console.log("issueToken error: " + JSON.stringify(err))
    });

}

标签: javascripttypescriptsettimeoutcleartimeout

解决方案


问题

setCanSendOtp(true)更新您的状态,将您的超时再次初始化为空。

解决方案

把你的超时放在参考。Ref 值在重新渲染和状态更新中是持久的。

const timeoutId:any = React.useRef(null);

const doOtp = ()=>{
        if(canSendOtp) {
            setCanSendOtp(false);

            timeoutId.current = setTimeout(() => { // it has here a numeric value
                showNotificationMessage("You can request OTP again")
                setCanSendOtp(true)
            }, SEND_OTP_TIME_CONSTRAINTS)

           // rest of doOtp logic
        }
        else {
            showNotificationMessage("Please wait " + (SEND_OTP_TIME_CONSTRAINTS / 1000) + " seconds before trying again")
        }
    }

const doLogin = () => {
issueToken(LOGIN_GRANT_TYPE, LOGIN_CLIENT_ID, LOGIN_CLIENT_SECRET, phoneNumber, otp)
    .then(res => { 
        
        if(timeoutId.current !== null) {
            clearTimeout(timeoutId.current)
        }

        store().dispatch(setTokenValidity(res))
    })
    .catch(err => {
        showNotificationMessage('Error, something went wrong check logs.')
        console.log("issueToken error: " + JSON.stringify(err))
    });


推荐阅读