【发布时间】:2023-02-09 01:22:59
【问题描述】:
第一次使用 clearInterval() 查看其他示例和间隔文档,这似乎是停止间隔的方法。不知道我错过了什么。
目的是在 currentStop 道具更新时终止计时器。
import React, { useEffect, useState } from 'react';
type Props = {
stopNumber: number;
currentStop: number;
};
const timerComponent = ({ stopNumber, currentStop }: Props) => {
let interval: NodeJS.Timer;
// Update elapsed on a timer
useEffect(() => {
if (stopNumber === currentStop) {
interval = setInterval(() => {
console.log('timer is running');
}, 3000);
// Clear interval on unmount
return () => clearInterval(interval);
}
}, []);
// Clear timers that were running
useEffect(() => {
if (stopNumber !== currentStop) {
clearInterval(interval);
}
}, [currentStop]);
};
【问题讨论】:
-
@pilchard 是的,看起来不使用
useRef()是我的错误。谢谢
标签: javascript reactjs setinterval