【问题标题】:React setState Date returns null - calculating date/timeReact setState Date 返回 null - 计算日期/时间
【发布时间】:2021-06-19 11:30:14
【问题描述】:

我想在 React 中计算时间差。稍后我想在数据库中发布当前日期并将其与当前时间进行比较,基本上是一个时间跟踪器。但是在设置状态时,它总是返回 0,我不明白为什么/还有什么其他选项?

const TimeComp = (props) => {
  const [Timer, setTimer] = useState(0)
  const [StartTime, setStartTime] = useState(0)

  const handleStart = () => {  
    setStartTime(new Date().getTime())
    setInterval(() => {
      console.log(StartTime)
      setTimer(new Date().getTime() - StartTime)
    }, 1000)
    }
  
    return (
      <div>
        <button onClick={handleStart}>Start</button>
          <h2> {Timer} </h2>
      </div>
            )
}

console.log(StartTime) 每次都返回 0,即使有间隔。 我希望它返回 unix 时间戳 ~ 1616440460597

setTimer(new Date().getTime() 然而成功返回了unix时间戳

感谢您的帮助

【问题讨论】:

    标签: javascript reactjs datetime time


    【解决方案1】:

    它在我使用的状态而不是使用状态时起作用

    const handleStart = () => {  
        let today = new Date().getTime()
        setInterval(() => {
          console.log(StartTime)
          setTimer(new Date().getTime() - today)
        }, 1000)
        }
    

    【讨论】:

      猜你喜欢
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 2011-07-10
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多