如何解决为什么在此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
调用箭头函数时,它不会传递任何参数,因此,swiss
是undefined
的原因。
编辑:您也可能会将真实的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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。