![](/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.