为什么我的时钟代码会减慢我的网站速度
Why is my clock code slowing my website down
我组装了一个基本时钟来使用 React Hooks,但出于某种原因,该工具包确实减慢了我的网站速度。有什么原因吗?
function Welcome() {
const [time, setTime] = useState(new Date());
setInterval(() => clock(), 1000);
function clock() {
setTime(new Date());
}
return (
<WelcomeBox>
<WelcomeTime>
{date.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true,
})}
</WelcomeTime>
</WelcomeBox>
);
}
不要在每次组件渲染时启动计时器
相反,您应该只启动一次计时器。
使用 setTimeout
而不是 setInterval
。
setTimeout
等待指定的时间,调用回调,然后离开,而 setInterval
一遍又一遍地调用回调,调用之间有延迟。
这是一个例子
function Welcome() {
// ...
function clock() {
setTime(new Date());
setTimeout(clock, 1000);
}
// ...
}
然后你可以调用一次clock()来启动时钟。
您在每次渲染组件时设置一个新的时间间隔。
要正确执行我认为您正在尝试执行的操作,您需要将 setInterval 放在 useEffect
挂钩中。
像这样:
function Welcome() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => clock(), 1000);
return () => clearInterval(interval)
}, [])
function clock() {
setTime(new Date());
}
return (
<WelcomeBox>
<WelcomeTime>
{date.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true,
})}
</WelcomeTime>
</WelcomeBox>
);
}
我组装了一个基本时钟来使用 React Hooks,但出于某种原因,该工具包确实减慢了我的网站速度。有什么原因吗?
function Welcome() {
const [time, setTime] = useState(new Date());
setInterval(() => clock(), 1000);
function clock() {
setTime(new Date());
}
return (
<WelcomeBox>
<WelcomeTime>
{date.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true,
})}
</WelcomeTime>
</WelcomeBox>
);
}
不要在每次组件渲染时启动计时器
相反,您应该只启动一次计时器。
使用 setTimeout
而不是 setInterval
。
setTimeout
等待指定的时间,调用回调,然后离开,而 setInterval
一遍又一遍地调用回调,调用之间有延迟。
这是一个例子
function Welcome() {
// ...
function clock() {
setTime(new Date());
setTimeout(clock, 1000);
}
// ...
}
然后你可以调用一次clock()来启动时钟。
您在每次渲染组件时设置一个新的时间间隔。
要正确执行我认为您正在尝试执行的操作,您需要将 setInterval 放在 useEffect
挂钩中。
像这样:
function Welcome() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => clock(), 1000);
return () => clearInterval(interval)
}, [])
function clock() {
setTime(new Date());
}
return (
<WelcomeBox>
<WelcomeTime>
{date.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true,
})}
</WelcomeTime>
</WelcomeBox>
);
}