定时器setTimeout、循环定时函数setInterval及闭包问题解决(setState失效)

超好用的定时器-轮播 循环执行等


  const timer = useRef(null); // 定时器

const
createTimer = () => { if (timer.current === null) { timer.current = setInterval(() => { // console.log(dataState === 'data1'); setState(); }, 2000); } }; const clearTimer = () => { clearInterval(timer.current); timer.current = null; };
 
setInterval方法中写入setState 设置值会导致setState方法失效:
一般解决办法:
1.在外部定义一个方法,然后在定时器内调用该方法
例如
const [dataState, setDataState] = useState('data1');
setDataState(dataState
=>{ //此处的dataState不是全局变量的dataState,而是作为dataState一个最新的值传给setDataState方法 return (新的dataState值) })

2.使用useRef (与useState等效)
const aaa=useRef(null);
aaa.current="初值"

 

posted @ 2022-08-04 18:38  SimoonJia  阅读(709)  评论(0编辑  收藏  举报