3

setInterval 等读取不到 useState 最新值的问题你们怎么解决?

 1 year ago
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.
neoserver,ios ssh client

V2EX  ›  React

setInterval 等读取不到 useState 最新值的问题你们怎么解决?

  estk · 4 小时 47 分钟前 · 502 次点击

如下,增加一个 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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK