代码之家  ›  专栏  ›  技术社区  ›  Yilmaz

type for useRef(如果与setInterval一起使用),react typescript

  •  1
  • Yilmaz  · 技术社区  · 5 年前

    我正在next.js应用程序中制作一个简单的动画。

    let flipInterval = useRef();
    
    
    
    const startAnimation = () => {
        flipInterval.current = setInterval(() => {
          setIsFlipping((prevFlipping) => !prevFlipping);
        }, 10000);
      };
    

    对于 flipInterval.current 我收到“类型'Timeout'不能分配给类型'undefined'”。所以我检查了如何使用Timeout类型,我看到人们正在使用但不起作用。

     let flipInterval = useRef<typeof window.settimeout>();
    

    我也传了号码 useRef<number>() 这次我得到“类型'Timeout'不能分配给类型'number'”

    这也不起作用

      let flipInterval = useRef<typeof window.setInterval>();
    
    1 回复  |  直到 4 年前
        1
  •  10
  •   Olcay Ozdemir    5 年前
     const intervalRef: { current: NodeJS.Timeout | null } = useRef(null);
    
    
    const startAnimation = () => {
       const id = setInterval(() => {
           setIsFlipping((prevFlipping) => !prevFlipping);
       }, 10000);
          intervalRef.current = id;
     };
    
      const clear = () => {
        clearInterval(intervalRef.current as NodeJS.Timeout);
      };
    
        2
  •  9
  •   buzatto    5 年前

    您需要传递正确的返回值类型 setInterval .用于此用途 ReturnType :

    const flipInterval = useRef<ReturnType<typeof setInterval>>(null)
    
        3
  •  8
  •   mirik999    5 年前

    我如何使用
    *最好设置useRef的initialValue。这就是为什么null。

      const timeout = useRef<NodeJS.Timeout | null>(null);
    
      timeout.current = setTimeout(() => someAction()), 500);
    
      useEffect(() => {
        return () => clearTimeout(timeout.current as NodeJS.Timeout);
      }, []);
    
        4
  •  3
  •   Michael Dimmitt    5 年前

    如果你正在取消公告,需要清除超时 null 需要处理

    由于问题的标题,这样发布可能会对其他人有所帮助。

    const flipInterval:{current: NodeJS.Timeout | null} = useRef(null)
    
    const startAnimation = () => {
      flipInterval.current && clearTimeout(scrollTimeout.current);
            
      flipInterval.current = setInterval(() => {
        setIsFlipping((prevFlipping) => !prevFlipping)
      }, 10000)
    }
    
        5
  •  0
  •   Darwinnirad    5 年前
    let flipInterval = useRef<number | null>(null);
    const startAnimation = () => {
      flipInterval.current = window.setInterval(() => {
        setIsFlipping((prevFlipping) => !prevFlipping);
      }, 10000);
    };
    
    /* way of clear interval */
    window.clearInterval(flipInterval.current || 0);
    
    
        6
  •  0
  •   kimbaudi    5 年前

    你需要使用 NodeJS.Timeout 类型:

    let flipInterval = useRef<NodeJS.Timeout>()
    
    const startAnimation = () => {
      flipInterval.current = setInterval(() => {
        setIsFlipping((prevFlipping) => !prevFlipping)
      }, 10000)
    }