useState+setInterval 导致获取useState都是原始的解决方法

 1 import { useRef, useEffect } from "react";
 2 export function useInterval(callback, delay) {
 3   const savedCallback = useRef();
 4 
 5   useEffect(() => {
 6     savedCallback.current = callback;
 7   });
 8 
 9   useEffect(() => {
10     function tick() {
11       savedCallback.current();
12     }
13 
14     if (delay !== null) {
15       let id = setInterval(tick, delay);
16       return () => clearInterval(id);
17     }
18   }, [delay]);
19 }


 

posted @ 2023-03-07 11:37  马铃薯头抽雪茄  阅读(147)  评论(0)    收藏  举报