在打字稿反应挂钩上声明带有接口的参数

Declare arguments with interface on typescript react hook

我正在尝试创建一个自定义挂钩来接收带有接口的 2 个类型化参数,但我收到一条消息 Expected 1 arguments, but got 2,我不确定我是在声明接口错误还是文件不能' t 是 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 }
}

混乱是由于您在这里进行的解构造成的: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 })