react native show current time and update the seconds in real-time

前端 未结 6 1842
说谎
说谎 2021-02-05 05:53

I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don

6条回答
  •  再見小時候
    2021-02-05 06:20

    in react hooks, it can be done like this:

    import React, { useState, useEffect } from "react";
    
    const [dt, setDt] = useState(new Date().toLocaleString());
    
    useEffect(() => {
        let secTimer = setInterval( () => {
          setDt(new Date().toLocaleString())
        },1000)
    
        return () => clearInterval(secTimer);
    }, []);
    

提交回复
热议问题