无法访问间隔内的状态



我无法在一段时间内访问状态。在这里,我想在间隔内访问计数器,当计数器等于10时,我想停止它

注意:这里我不想将间隔放在useEffect中,因为我需要通过处理事件在特定时间开始间隔。

export default props => {
const [counter, setCounter] = useState(0);
const startInterval = () => {
const timeout = setInterval(() => {
setCounter(counter + 1);
console.log("counter: ", counter); // alway return 0
if(counter === 10) clearInterval(timeout);
}, 1000);
};
} 

正如我在这里看到的,由于词法范围的原因,即使您的setCounter(counter+1)也不会更新。所以你必须这样改变:

setCounter(counter => counter + 1);

此外,由于词法范围的原因,您无法访问counter来检查条件,因此您必须创建一个变量,并通过向其添加counter来更新函数组件内部的变量,然后使用if条件进行检查。

完整代码:

let myCounter = 0;
let timeout = null;
export default CounterApp = props => {
const [counter, setCounter] = useState(0);
// Also don't forget this
useEffect(()=> {
return ()=> clearInterval(timeout);
}, []);      
myCounter = counter;
const startInterval = () => {
timeout = setInterval(() => {
setCounter(counter => counter + 1);
console.log("counter: ", myCounter); // counter always return 0 but myCounter the updated value
if(myCounter === 10) clearInterval(timeout);
}, 1000);
};
}

不久前我遇到了这个问题。挂钩的工作方式并不像您所期望的那样与setInterval相关。我在Dan Abramov的博客上找到了解决方案:你可以useRef来组合多个useEffect。通过他的useInterval实现,你也可以通过将计时器设置为null来启动和停止间隔

import React, { useState, useEffect, useRef } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const [time, setTime] = useState(null); // timer doesn't run initially
useInterval(() => {
// Your custom logic here
setCount(count + 1);
}, time);
return <>
<h1>{count}</h1>
<div onClick={() => setTime(1000)}>Start</div>
<div onClick={() => setTime(null)}>Stop</div>
</>;
}
import React, { useState, useEffect, useRef } from 'react';
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}

相关内容

  • 没有找到相关文章

最新更新