[英]Why my variable "intervalId" is not getting the value updated when I call the function "StopTimer" function?
Here is my simple code:这是我的简单代码:
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 这是错误的表示
I press Start Time button and then the Stop Time Button , but my variable intervalId in the stopTimer function is not getting the updated value from the setInterval function.我按下Start Time 按钮,然后按下Stop Time Button ,但是我在 stopTimer 函数中的变量 intervalId 没有从 setInterval 函数中获取更新的值。 Why?.
为什么?。
Because intervalId
is not the same variable that was in scope when startTimer
was invoked.因为
intervalId
与调用startTimer
时作用域内的变量不同。 It will be undefined
in all the subsequent renders.它将在所有后续渲染中
undefined
。 ( caused when time
change state ) (当
time
改变状态时引起)
In React, if you want to "keep a value" across the life cycle of a component, you can use a ref
for it:在 React 中,如果你想在组件的整个生命周期中“保持一个值”,你可以为它使用
ref
:
// ....
var intervalId = React.useRef();
// ....
intervalId.current = setInterval(() => {
// ...
clearInterval(intervalId.current);
Since the App
is invoked everytime you change the state ( setTime
), you get a new, fresh value of the local variable.由于每次更改状态 (
setTime
) 时都会调用App
,因此您将获得局部变量的新值。
One of options is to include the variable in your state.一种选择是在您的状态中包含变量。
function App() {
var [time, setTime] = useState(0);
var [intervalId, setIntervalId] = useState(0);
function startTimer() {
setIntervalId(intervalId => setInterval(() => {
setTime(time => time + 1);
}, 1000));
}
function stopTimer() {
clearInterval(intervalId);
}
return (
<div className="App">
<div>{time}</div>
<div>
<button onClick={startTimer}>Start time</button>
<button onClick={stopTimer}>Stop time</button>
</div>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.