useRef 的类型(如果与 setInterval、react-typescript 一起使用)

Yil*_*maz 26 animation settimeout typescript reactjs next.js

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

let flipInterval = useRef();



const startAnimation = () => {
    flipInterval.current = setInterval(() => {
      setIsFlipping((prevFlipping) => !prevFlipping);
    }, 10000);
  };
Run Code Online (Sandbox Code Playgroud)

因为flipInterval.current我收到“类型‘超时’不能分配给类型‘未定义’”。所以我检查了如何使用超时类型,我看到人们正在使用,但那不起作用。

 let flipInterval = useRef<typeof window.settimeout>();
Run Code Online (Sandbox Code Playgroud)

我也通过了号码useRef<number>()我收到“类型‘超时’不能分配给类型‘数字’”

这也不起作用

  let flipInterval = useRef<typeof window.setInterval>();
Run Code Online (Sandbox Code Playgroud)

buz*_*tto 36

您需要传递正确的返回值类型setInterval。为此用途ReturnType

const flipInterval = useRef<ReturnType<typeof setInterval> | null>(null)
Run Code Online (Sandbox Code Playgroud)

  • 通过执行 `useRef&lt;ReturnType&lt;typeof setInterval&gt; | 解决 null&gt;(null)` 或者 `useRef&lt;ReturnType&lt;typeof setInterval&gt;&gt;()` (5认同)
  • 应用此后我收到一个新错误:“无法分配给‘当前’,因为它是只读 property.ts (2540)” (4认同)

小智 16

 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);
  };
Run Code Online (Sandbox Code Playgroud)


小智 14

我如何使用
*最好设置 useRef 的初始值。这就是为什么为空。

  const timeout = useRef<NodeJS.Timeout | null>(null);

  timeout.current = setTimeout(() => someAction()), 500);

  useEffect(() => {
    return () => clearTimeout(timeout.current as NodeJS.Timeout);
  }, []);
Run Code Online (Sandbox Code Playgroud)