【问题标题】:Declare arguments with interface on typescript react hook在打字稿反应钩子上用接口声明参数
【发布时间】:2021-11-22 10:44:12
【问题描述】:

我正在尝试创建一个自定义挂钩,它接收带有接口的 2 个类型化参数,但我收到一条消息 Expected 1 arguments, but got 2,我不确定我是否声明接口错误或文件不能是 tsx

文件index.tsx

const [thisPage, setThisPage] = useState(1)

const changePage = (newNumber?: number): void => {
  console.log(newNumber ?? thisPage)
}

const { goNext, goBack } = useSideButtons(changePage, setThisPage)

文件useSideButtons.tsx

import { useEffect, SetStateAction } from 'react'

interface ISideButtons {
  changePage: (newNumber?: number) => void
  setThisPage: (value: SetStateAction<number>) => void
}

interface ISideExports {
  goNext: () => void
  goBack: () => void
}

export default function useSideButtons ({ changePage, setThisPage }: ISideButtons): ISideExports {
  useEffect(changePage, [])

  const goNext = (): void => {
    setThisPage((actual) => {
      const newNumber = actual + 1
      return newNumber
    })
  }

  const goBack = (): void => {
    setThisPage(actual => {
      if (actual > 1) {
        const newNumber = actual - 1
        changePage(newNumber)
        return newNumber
      } else {
        return 1
      }
    })
  }

  return { goNext, goBack }
}

我知道这样使用是可行的,但我想声明一个接口以使代码更易于阅读:

import { useEffect, SetStateAction } from 'react'

interface ISideExports {
  goNext: () => void
  goBack: () => void
}

export default function useSideButtons (
  changePage: (newNumber?: number) => void,
  setThisPage: (value: SetStateAction<number>) => void
): ISideExports {
  useEffect(changePage, [])

  const goNext = (): void => {
    setThisPage((actual) => {
      const newNumber = actual + 1
      localStorage.setItem('instandaThisPage', String(newNumber))
      return newNumber
    })
  }

  const goBack = (): void => {
    setThisPage(actual => {
      if (actual > 1) {
        const newNumber = actual - 1
        changePage(newNumber)
        localStorage.setItem('instandaThisPage', String(newNumber))
        return newNumber
      } else {
        return 1
      }
    })
  }

  return { goNext, goBack }
}

【问题讨论】:

    标签: reactjs typescript react-hooks tsx react-tsx


    【解决方案1】:

    混乱是由于你在这里做的解构:function useSideButtons ({ changePage, setThisPage }: ISideButtons)

    此代码表示只有一个参数,而不是两个。类似于写法

    function useSideButtons (sideButtons: ISideButtons) {
        const changePage = sideButtons.changePage;
        const setThisPage = sideButtons.setThisPage;
        // Rest of your code
    
    }
    

    如您在上面的示例中所见,该函数只有 1 个参数。

    因此,您可能打算传递一个包含两个值的对象,而不是像这样传递两个参数:useSideButtons(changePage, setThisPage)useSideButtons({ changePage, setThisPage })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-06
      • 2019-03-26
      • 1970-01-01
      • 2019-04-19
      • 2021-01-03
      • 2020-01-28
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多