为什么在此setInterval中未定义此useRef值?

问题描述

为什么在此swiss中引用undefined setInterval

每次迭代都传递swiss的值。

export default function cheese() {
    const swiss = useRef("Jarlsberg")
    const myInterval = useRef()
    myInterval.current = setInterval ( swiss => {
        console.log(swiss) //-> undefined
        console.log(swiss.current) //-> Error b/c undefined has no properties
    },997)
}

解决方法

这是因为您使用的setInterval错误。在箭头函数中,您将swiss作为参数,而不是参数(您要传递的值)。 setInterval调用箭头函数时,它不会传递任何参数,因此,swissundefined的原因。

编辑:您也可能会将真实的swiss值“隐藏”在参数名称中。经过我的测试,如果您删除参数或更改其名称,则swiss调用中可以使用setInterval

export default function cheese() {
    const swiss = useRef("Jarlsberg")
    const myInterval = useRef();
    myInterval.current = setInterval ( () => { // note the change from `swiss` to an empty ().
        console.log(swiss) //-> exists!
        console.log(swiss.current) //-> Jarlsberg
    },997)
}