【问题标题】:'setDate' is not defined no-undef'setDate' 未定义 no-undef
【发布时间】:2021-05-22 02:30:17
【问题描述】:

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

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 reactjs compiler-errors


【解决方案1】:

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();
&lt;div id="clock"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 2018-06-09
    • 2018-10-02
    • 2021-05-26
    • 2021-06-17
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多