React:每秒重新渲染时钟的组件

问题描述 投票:0回答:1

我制作了代表 HH:MM 时钟的组件。 它每秒都在重新渲染。我希望每分钟都重新渲染。 其上附有一个工具提示。由于重新渲染,无法显示工具提示。 我该如何处理这种情况?

import TooltipComp from '@components/Shared/TooltipComp'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'

const Clock = () => {
    const [Time, setTime] = useState(new Date())
    const { t } = useTranslation();

    useEffect(() => {
        let now = new Date()
        while (now.getSeconds() !== 0) {
            const interval = window.setInterval(() => {now = new Date()}, 1000)
            return () => window.clearInterval(interval);
        }
        setTime(now);
    }, [])
    
    const formatTime = (time) => {
        return time < 10 ? `0${time}` : time
    }

    const date = Time.toLocaleDateString(t('locale'), {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    })

    return (
    <>
        <TooltipComp text={date}>
            <div style={{fontSize: "9px", fontFamily: "PX", cursor: "default"}}>
                {formatTime(Time.getHours())}
                &thinsp;:&thinsp;
                {formatTime(Time.getMinutes())}
            </div>
        </TooltipComp>
    </>
  )

  
}

export default Clock

我已经尝试过使用 useMemo 钩子,以及 useEffect 钩子的多种变体。

javascript reactjs render real-time-clock
1个回答
0
投票

每秒重新渲染应该不会有问题。事实上,在这样的时钟中,这应该是可取的。您检查过您的时钟是否正常工作吗?

  useEffect(() => {
        let now = new Date()
        while (now.getSeconds() !== 0) {
            const interval = window.setInterval(() => {now = new Date()}, 1000)
            return () => window.clearInterval(interval);
        }
        setTime(now);
    }, [])

您似乎在设置状态之前就退出了 useEffect。这意味着您的 UI 将不会收到任何状态更新。

useEffect(() => {
    // Adjust this to 60 * 1000 for 1 min (not required)
    const refreshTime = 1000;
    const interval = setInterval(() => {
      setTime(new Date())
    }, refreshTime)

    return () => {
      clearInterval(interval)
    }
  }, []);
© www.soinside.com 2019 - 2024. All rights reserved.