【发布时间】:2020-02-29 16:41:01
【问题描述】:
这是我的简单代码:
import React, { useState } from "react";
import "./App.css";
function App() {
const [time, setTime] = useState(0);
var intervalId;
function startTimer() {
intervalId = setInterval(() => {
setTime(time => time + 1);
}, 1000);
console.log("My interval id is: ", intervalId);
}
function stopTimer() {
console.log("Clearing intervalId", intervalId);
clearInterval(intervalId);
}
return (
<div className="App">
<div>{time}</div>
<div>
<button onClick={startTimer}>Start time</button>
<button onClick={stopTimer}>Stop time</button>
</div>
</div>
);
}
Here is the representation of the error
我按开始时间按钮,然后按停止时间按钮,但我在stopTimer 函数中的变量intervalId 没有从setInterval 函数获取更新值。为什么?
【问题讨论】:
标签: javascript reactjs