|
@@ -0,0 +1,67 @@
|
|
|
|
|
+/* eslint-disable */
|
|
|
|
|
+import { useEffect, useState } from 'react'
|
|
|
|
|
+import { useMount, usePersistFn } from '_ahooks@2.10.2@ahooks'
|
|
|
|
|
+import { Target } from '_ahooks@2.10.2@ahooks/lib/useScroll'
|
|
|
|
|
+import { getTargetElement } from '_ahooks@2.10.2@ahooks/lib/utils/dom'
|
|
|
|
|
+
|
|
|
|
|
+type requestBasicParams = {
|
|
|
|
|
+ current: number
|
|
|
|
|
+ pageSize: number
|
|
|
|
|
+}
|
|
|
|
|
+/**
|
|
|
|
|
+ * @description 适用于列表、表格滚动加载下一页数据
|
|
|
|
|
+ */
|
|
|
|
|
+export function useScrollRequest(
|
|
|
|
|
+ pageSize: number,
|
|
|
|
|
+ requestFn?: (params: requestBasicParams) => Promise<number>,
|
|
|
|
|
+ target?: Target
|
|
|
|
|
+) {
|
|
|
|
|
+ if (!requestFn) return
|
|
|
|
|
+ const [state, setState] = useState({
|
|
|
|
|
+ current: 1,
|
|
|
|
|
+ total: 0
|
|
|
|
|
+ })
|
|
|
|
|
+
|
|
|
|
|
+ const requestFnPersist = usePersistFn(requestFn)
|
|
|
|
|
+ // 初始化执行
|
|
|
|
|
+ useMount(() => {
|
|
|
|
|
+ requestFnPersist({ current: state.current, pageSize }, (total: number) => {})
|
|
|
|
|
+ setState({ ...state, total: 20 })
|
|
|
|
|
+ })
|
|
|
|
|
+ useEffect(() => {
|
|
|
|
|
+ const el = getTargetElement(target, document)
|
|
|
|
|
+ console.log(state.total, state.current)
|
|
|
|
|
+ if (!el) return
|
|
|
|
|
+ async function requestNextData(currentTarget: Target) {
|
|
|
|
|
+ // 判断是否以及加载了最后的列表
|
|
|
|
|
+ console.log(state.total, state.current)
|
|
|
|
|
+
|
|
|
|
|
+ if (!state.total || state.current * pageSize > state.total) return
|
|
|
|
|
+ let total
|
|
|
|
|
+ // 没有拿到ref对应的dom元素,则直接那document中正在滚动的元素
|
|
|
|
|
+ if (currentTarget === document) {
|
|
|
|
|
+ if (!document.scrollingElement) return
|
|
|
|
|
+ if (
|
|
|
|
|
+ document.scrollingElement.scrollTop + document.scrollingElement.clientHeight ===
|
|
|
|
|
+ document.scrollingElement.scrollHeight
|
|
|
|
|
+ ) {
|
|
|
|
|
+ await requestFnPersist({ current: state.current + 1, pageSize })
|
|
|
|
|
+ // setState({ ...state, current: state.current + 1, total })
|
|
|
|
|
+ }
|
|
|
|
|
+ } else {
|
|
|
|
|
+ if (currentTarget.scrollTop + currentTarget.clientHeight === currentTarget.scrollHeight) {
|
|
|
|
|
+ await requestFnPersist({ current: state.current + 1, pageSize })
|
|
|
|
|
+ console.log('end-', total)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ setState({ ...state, current: state.current + 1 })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function listener(event: EventListenerOrEventListenerObject) {
|
|
|
|
|
+ if (!event.target) return
|
|
|
|
|
+ requestNextData(event.target)
|
|
|
|
|
+ }
|
|
|
|
|
+ el.addEventListener('scroll', listener)
|
|
|
|
|
+ return () => el.removeEventListener('scroll', listener)
|
|
|
|
|
+ }, [target])
|
|
|
|
|
+}
|