繁体   English   中英

'setDate' 未定义 no-undef

[英]'setDate' is not defined no-undef

我正在尝试向我的网站添加当前时间功能,但我的代码遇到了问题。 当我运行我的代码时,它无法编译,但是当您检查页面时,您可以看到正在显示的时间。 这是我的代码。

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,我找到了解决该问题的方法。 这是解决方法。 不要忘记像我一样导入您的 javascript 文件。 快乐的黑客攻击:)

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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