0

重载不匹配

import React, { useEffect, useState, useRef } from 'react'


function Button() {

  const [ctr, setCtr] = useState(0)
  let interval = useRef<NodeJS.Timeout | null>(null)

  useEffect(() => {
    interval.current = setInterval(() => {
      setCtr(prev => prev + 1)
    },1000)
    return () => {
      clearInterval(interval.current)
    }
  }, [])
  
 
  return (
    <>
      <span> Count : {ctr} </span>
      <button onClick={ () => clearInterval(interval.current) }> Clear </button>
    </>
  )
}

export default Button

错误:

No overload matches this call.
  Overload 1 of 2, '(intervalId: Timeout): void', gave the following error.
    Argument of type 'Timeout | null' is not assignable to parameter of type 'Timeout'.
      Type 'null' is not assignable to type 'Timeout'.
  Overload 2 of 2, '(handle?: number | undefined): void', gave the following error.
    Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'.
      Type 'null' is not assignable to type 'number | undefined'.ts(2769)

图片:

在此处输入图像描述

4

2 回答 2

1

您需要null从类型中排除interval.current

<button onClick={ () => clearInterval(interval.current as Timeout) }> Clear </button>
于 2020-11-29T07:36:50.740 回答
0

我忘记了 setInterval 是一个窗口对象。这里的问题是 TS 认为这是一个 NodeJS 构造,而它只是一个窗口函数。使用as关键字不是好的做法,在大多数情况下应避免使用。打字稿的全部意义在于它是强类型的,并且使用as偏离了它。

function Button() {

  const [ctr, setCtr] = useState(0)
  const interval = useRef(0);
  useEffect(() => {
    interval.current = window.setInterval(() => {
      setCtr(prev=>prev+1)
    }, 1000);

    return () => {
      window.clearInterval(interval.current);
    };
  }, []);
  
 
  return (
    <>
      <span> Count : {ctr} </span>
      <button onClick={ () => window.clearInterval(interval.current) }> Clear </button>
    </>
  )
}
于 2020-11-29T07:52:15.640 回答