Javascript 更新的状态值未反映在React中的setInterval()中
我有以下资料:Javascript 更新的状态值未反映在React中的setInterval()中,javascript,reactjs,Javascript,Reactjs,我有以下资料: const [isPaused, setIsPaused] = useState(false); const myTimer = useRef(null); const startTimer = () => { myTimer.current = setInterval(() => { console.log(isPaused); // always says "false" }, 1000); }; 当计时器运行时,我正在更新
const [isPaused, setIsPaused] = useState(false);
const myTimer = useRef(null);
const startTimer = () => {
myTimer.current = setInterval(() => {
console.log(isPaused); // always says "false"
}, 1000);
};
当计时器运行时,我正在更新isPaused
的值:
setIsPaused(true);
但这并没有反映在控制台日志中,它总是记录为false。有解决办法吗?你可以这样做
const [isPaused, setIsPaused] = useState(false);
const myTimer = useRef(null);
const startTimer = () => {
myTimer.current = setInterval(() => {
console.log(isPaused); // now updates
}, 1000);
};
useEffect(() => {
startTimer();
return () => myTimer.current != null && clearInterval(myTimer.current);
}, [isPaused]);
return (
<div>
<b>isPaused: {isPaused ? "T" : "F"}</b>
<button onClick={() => setIsPaused(!isPaused)}>Toggle</button>
</div>
);
或者,使用软件包
函数计数器(){
let[count,setCount]=useState(0);
const increaseCount=金额=>{
设置计数(计数+金额);
};
使用间隔(递增计数,1000,5);
返回{count};
}
您可以这样做
const [isPaused, setIsPaused] = useState(false);
const myTimer = useRef(null);
const startTimer = () => {
myTimer.current = setInterval(() => {
console.log(isPaused); // now updates
}, 1000);
};
useEffect(() => {
startTimer();
return () => myTimer.current != null && clearInterval(myTimer.current);
}, [isPaused]);
return (
<div>
<b>isPaused: {isPaused ? "T" : "F"}</b>
<button onClick={() => setIsPaused(!isPaused)}>Toggle</button>
</div>
);
或者,使用软件包
函数计数器(){
let[count,setCount]=useState(0);
const increaseCount=金额=>{
设置计数(计数+金额);
};
使用间隔(递增计数,1000,5);
返回{count};
}
当前的myTimer.current
从未更改,这意味着isPaused
在函数中总是false
您需要使用useffect
来更新myTimer。每次更新isPaused
时,当前的
useEffect(() => {
function startTimer() {
myTimer.current = setInterval(() => {
console.log(isPaused);
}, 1000);
};
startTimer();
return () => clearInterval(myTimer.current); // cleanup
}, [isPaused]);
myTimer.current
从未更改,这意味着函数中的isPaused
始终为false
您需要使用useffect
来更新myTimer。每次更新isPaused
时,当前的
useEffect(() => {
function startTimer() {
myTimer.current = setInterval(() => {
console.log(isPaused);
}, 1000);
};
startTimer();
return () => clearInterval(myTimer.current); // cleanup
}, [isPaused]);
谢谢我知道这里发生了什么,当isPaused的值改变时,你正在创建一个新的间隔,每次都清除旧的间隔,对吗?也可以像以前一样将它定义为startTimer
的值,这样我就可以像这样调用它startTimer()
?是的,你说得对useffect()
将在每次渲染后清除计时器(当isPaused
更改时,请参见[isPaused]
是效果的依赖项)。对您也可以将startTimer()
放入useffect()
中。见更新。谢谢!我知道这里发生了什么,当isPaused的值改变时,你正在创建一个新的间隔,每次都清除旧的间隔,对吗?也可以像以前一样将它定义为startTimer
的值,这样我就可以像这样调用它startTimer()
?是的,你说得对useffect()
将在每次渲染后清除计时器(当isPaused
更改时,请参见[isPaused]
是效果的依赖项)。对您也可以将startTimer()
放入useffect()
中。请参阅已更新。useffect()
将在每次渲染后运行,而不是在isPaused
更改时运行。useffect()
将在每次渲染后运行,而不是在isPaused
更改时运行。