The only time clearInterval
is ever called, id
is undefined. (That is, it's declared as a variable within that function's scope but has no value set to it.) You need to store the value of that id
so you can access it later. Since this is a React component, state is a reasonable place to store it. For example:
const [intervalId, setIntervalId] = useState(0);
Then set that state when setting the interval:
setIntervalId(setInterval(() => setSeconds(sec => sec + 1), 1000));
And then when you clear the interval you can use the ID value from state:
clearInterval(intervalId);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…