123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
- import { ScrollView } from '@tarojs/components';
- import Taro from '@tarojs/taro';
-
- export default (props) => {
- const {
- render,
- request,
- params,
- pageSize = 10,
- onError,
- onDataChange,
- ...leftProps
- } = props
-
- const loadingRef = useRef(false)
- const [payload, setPayload] = useState({})
- const [list, setList] = useState([])
- const pageRef = useRef({ current: 1, pages: 0 })
- const hasMore = pageRef.current.current < pageRef.current.pages
-
- // 滚动
- const handleScrollToLower = (e) => {
- const loading = loadingRef.current
-
- if (!loading && hasMore) {
- setPayload({
- ...payload,
- pageNum: pageRef.current.current + 1
- })
- }
- }
-
- const fetchList = (queryParams) => {
- if (!request) return;
-
- Taro.showLoading()
- loadingRef.current = true
- request(queryParams).then((res) => {
- const { records, ...pageInfo } = res || {}
- const lst = pageInfo.current === 1 ? records || [] : list.concat(records || [])
- setList(lst)
- if (onDataChange) {
- onDataChange(lst)
- }
-
- pageRef.current = pageInfo
- loadingRef.current = false
- Taro.hideLoading()
- }).catch((err) => {
- loadingRef.current = false
- console.error(err)
- Taro.hideLoading()
- if (onError) {
- onError(err)
- }
- })
- }
-
- const fetchRef = useRef()
- fetchRef.current = fetchList
-
- // 联动状态, 设置查询参数
- useEffect(() => {
- setPayload({
- ...params || {},
- pageNum: 1,
- pageSize,
- })
- }, [pageSize, params])
-
- // 请求数据
- useEffect(() => {
- fetchRef.current(payload)
- }, [payload])
-
- return (
- <ScrollView
- scrollY
- onScrollToLower={handleScrollToLower}
- {...leftProps}
- >
- {!render
- ? props.children
- : list.map((item, index) => render({ item, index }))
- }
- <view className='botton' style={{ display: hasMore ? 'none' : '' }}>已经到底了~</view>
- </ScrollView>
- )
- }
|