![](/img/trans.png)
[英]If I have a variable, assigned to the value of a function call, can that variable be updated if the function call's parameters are changed?
[英]Why my variable "intervalId" is not getting the value updated when I call the function "StopTimer" function?
这是我的简单代码:
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>
);
}
我按下Start Time 按钮,然后按下Stop Time Button ,但是我在 stopTimer 函数中的变量 intervalId 没有从 setInterval 函数中获取更新的值。 为什么?。
因为intervalId
与调用startTimer
时作用域内的变量不同。 它将在所有后续渲染中undefined
。 (当time
改变状态时引起)
在 React 中,如果你想在组件的整个生命周期中“保持一个值”,你可以为它使用ref
:
// ....
var intervalId = React.useRef();
// ....
intervalId.current = setInterval(() => {
// ...
clearInterval(intervalId.current);
由于每次更改状态 ( setTime
) 时都会调用App
,因此您将获得局部变量的新值。
一种选择是在您的状态中包含变量。
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.