簡體   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