gpt4 book ai didi

reactjs - 带有通用类型的自定义 Hook TypeScript

转载 作者:行者123 更新时间:2023-12-03 08:36:54 27 4
gpt4 key购买 nike

我在为自定义 Hook usePagination 创建接口(interface)时遇到问题。我需要帮助来创建这个通用的钩子(Hook),因为此时 User 接口(interface)与其余接口(interface)不相关。 dataEntries 是具有 id、firstName 和 lastName 的用户数组。 ElementsOnPage 默认设置为 50。

function usePagination(dataEntries,elementsOnPage = 50) {
const [actualPageIdx, setActualPageIdx] = useState(1)
const lastPageIdx = Math.ceil(dataEntries.length / elementsOnPage)
const [isBusy, setIsBusy] = useState(false)
const timeoutRef = useRef<any>(null)


useEffect(() => {
setIsBusy(true)
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
}
timeoutRef.current = setTimeout(() => {
setIsBusy(false)
}, 333)
}, [actualPageIdx])

const entriesOnSelectedPage = () => {
const firstEntry = (actualPageIdx - 1) * elementsOnPage
const lastEntry = firstEntry + elementsOnPage
console.log(dataEntries.slice(firstEntry, lastEntry))
return dataEntries.slice(firstEntry, lastEntry)
}

const goToFirstPage = useCallback(() => {
setActualPageIdx(1)
}, [])

const goToLastPage = () => {
setActualPageIdx(lastPageIdx)
}

const goToPage = (page: number) => {
setActualPageIdx(page)
}

const goToPrevPage = () => {
setActualPageIdx((actualPageIdx) => (actualPageIdx === 1 ? actualPageIdx : actualPageIdx - 1))
}

const goToNextPage = () => {
setActualPageIdx((actualPageIdx) =>
actualPageIdx === lastPageIdx ? actualPageIdx : actualPageIdx + 1
)
}

return [
{ actualPageIdx,
lastPageIdx,
entriesOnSelectedPage,
isBusy },
{
goToFirstPage,
goToPrevPage,
goToPage,
goToNextPage,
goToLastPage,
},
]
}

我尝试过这样做:

interface User {
id: number
firstName: string
lastName: string
}

interface PaginationState {
lastPageIdx: number
actualPageIdx: number
entriesOnSelectedPage: () => User[]
isBusy: boolean
}

interface PaginationActions {
goToFirstPage: () => void
goToPrevPage: () => void
goToNextPage: () => void
goToLastPage: () => void
goToPage: (number: number) => void
}

但我想使用泛型类型来检索这样的东西:

function usePagination<T>(dataEntries: T[], elementsOnPage = 50): [PaginationState, PaginationActions] {

return [
{ actualPageIdx,
lastPageIdx,
entriesOnSelectedPage,
isBusy },
{
goToFirstPage,
goToPrevPage,
goToPage,
goToNextPage,
goToLastPage,
},
]
}

最佳答案

你几乎已经拥有它了。你只需要让你的PaginationState接口(interface)通用:

interface PaginationState<T> {
lastPageIdx: number
actualPageIdx: number
entriesOnSelectedPage: () => T[]
isBusy: boolean
}

然后通过TPaginationState在你的usePagination功能。

function usePagination<T>(
dataEntries: T[],
elementsOnPage = 50
): [PaginationState<T>, PaginationActions] {
//...
}

现在usePagination可以推断它的泛型类型并将其传递给 PaginationState<T>

const users: User[] = []
const [state, action] = usePagination(users) // state has type PaginationState<User>

Playground

关于reactjs - 带有通用类型的自定义 Hook TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63674219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com