【问题标题】:Overloads don't match on useRef重载与 useRef 不匹配
【发布时间】:2020-11-29 07:34:27
【问题描述】:

重载不匹配

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)

图片:

【问题讨论】:

    标签: javascript reactjs use-ref


    【解决方案1】:

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

    <button onClick={ () => clearInterval(interval.current as Timeout) }> Clear </button>
    

    【讨论】:

      【解决方案2】:

      我忘记了 setInterval 是一个窗口对象。这里的问题是 TS 认为这是一个 NodeJS 构造,而它只是一个窗口函数。使用 as 关键字不是好的做法,在大多数情况下应避免使用。 typescript 的重点在于它是强类型的,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>
          </>
        )
      }
      

      【讨论】:

        猜你喜欢
        • 2019-08-12
        • 2021-03-01
        • 2018-10-14
        • 1970-01-01
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 2020-03-04
        • 2017-08-10
        相关资源
        最近更新 更多