3
setInterval 等读取不到 useState 最新值的问题你们怎么解决?
source link: https://www.v2ex.com/t/889077
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
如下,增加一个 timeDateG 不是最优雅的方式吧?
import { useEffect, useState } from "react"
let timeDateG = '00:00:00'
const UseStateIssue = () => {
const [timeDate, setTimeDate] = useState('00:00:00')
useEffect(()=>{
timeDateG = timeDate
}, [timeDate])
useEffect(()=>{
const interval = setInterval(()=>{
console.log('timeDate', timeDate) // 一直是 '00:00:00'
console.log('timeDateG', timeDateG) // 解决方法 1
}, 2000)
return () => clearInterval(interval)
}, [])
return (
<div>
<div>{timeDate},这里正常刷新</div>
<button onClick={()=>{
setTimeDate(new Date().toLocaleTimeString())
}}>setTimeDate</button>
</div>
)
}
export default UseStateIssue
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK