简体   繁体   中英

'setDate' is not defined no-undef

I'm trying to add a current time feature to my website and I ran into a problem with my code. When I run my code, it fails to compile, but when you inspect the page you can see the time being displayed. Here's my code.

import React, { useState, useEffect } from 'react';

export const DateTime = () => {

var [date,setDate] = useState(new Date());

useEffect(() => {

    var timer = setInterval(()=>setDate(new Date()), 1000 )

    return function cleanup() {
        clearInterval(timer)
    }

});

return(
    <div>
        <p>Time : {date.toLocaleTimeString()}</p>
    </div>
)

}

export default DateTime;

nvm, I found a workaround to the problem. Here's the workaround. don't forget to import your javascript file as I did. Happy hacking:)

 const clock = document.getElementById('clock'); const dateLocal = 'en-US'; const dateFormat = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const clockFn = () => { const now = new Date(); const time = now.toLocaleTimeString().split(':').splice(0, 2).join(':'); const date = now.toLocaleDateString(dateLocal, dateFormat); clock.dataset.time = time; clock.dataset.date = date; }; setInterval(() => { clockFn(); }, 1000) clockFn();
 <div id="clock"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM