题意:在 React 中创建时钟
问题背景:
I have a website and I want to put a realtime clock on one of the pages. I have written the code using hooks but I understand using hooks for such cases is bad for performance due to rerenders in states every second. Is there a less resource intensive solution?
我有一个网站,我想在其中一页上放置一个实时时钟。我已经使用钩子(hooks)编写了代码,但我了解到,由于状态每秒都会重新渲染,所以在这种情况下使用钩子对性能不利。有没有一种资源消耗较少的解决方案?
import { useEffect, useState } from 'react'
export default function Footer() {
const [time, setTime] = useState()
useEffect(() => {
setInterval(() => {
const dateObject = new Date()
const hour = dateObject.getHours()
const minute = dateObject.getMinutes()
const second = dateObject.getSeconds()
const currentTime = hour + ' : ' + minute + ' : ' + second
setTime(currentTime)
}, 1000)
}, [])
return <div>{time}</div>
}
问题解决:
It's definitely good that you're thinking about performance however in this situation I wouldn't change a single thing. In order to change what gets rendered to the screen (in this case the text of the clock), the component has to be re-rendered to reflect the change in it's state, which is not such a bad thing. Each time the component re-renders it's not going to cause the parent to re-render so performance-wise we're doing just fine.
你考虑性能问题肯定是好的,但在这种情况下,我不会改变任何东西。为了改变屏幕上显示的内容(在这个例子中是时钟的文本),组件必须重新渲染以反映其状态的变化,这并不是什么坏事。每次组件重新渲染时,都不会导致父组件重新渲染,所以从性能角度来看,我们做得很好。