繁体   English   中英

如何乘以方法调用的数量来获取下一页数据(无限滚动分页)

[英]How to multiply the number of method calls to fetch next page data (infinite scrolling pagination)

我目前正在通过应用useState挂钩来实现无限滚动分页功能。 下面看到的fetchMoreListItems() function 使用每个后续.follow('next')调用从 API 获取下一页。 例如.follow('next').follow('next').followAll('item')将获取第 3 页上的所有记录。

这种逻辑可能听起来很愚蠢,但我实际上是在尝试找到一种有效的方法来“乘以” .follow('next')方法调用的数量乘以setPage()设置的页码以将适当的数据获取到 append 到用户滚动到底部时的 DOM。 例如,如果通过无限滚动我们当前看到所有数据直到第 3 页,那么当用户向下滚动时,我需要.follow('next') * 3来获取第 4 页数据。 有没有办法分解这一系列方法调用,这样如果我想要第 4 页数据,那么我可以做这样的事情,而不是调用.follow('next') 3 次: .follow('activity-collection') +.follow('next') * 3 +.followAll('item')

const [items, setItems] = useState<Resource<Activity>[]>();
const [isFetching, setIsFetching] = useState(false);
const [page, setPage] = useState(1);

useEffect(() => {
    if (!props.resource) return;
    props.resource
      .follow('activity-collection').followAll('item')
      .then(resources => {
        setItems(resources);
        console.log(resources);
      })
      .catch(err => console.error('Error fetching resources: ' + err));
  }, [activityResource]);

function fetchMoreListItems() {
    setTimeout(() => {
      if (page >= 1) {
        props.resource
          // This line currently retrieves page 2 information 
          // every subsequent .follow('next') fetches the next page
          .follow('activity-collection').follow('next').followAll('item')
          .then(resources => {
            setItems([...items, ...resources]);
            console.log([...items, ...resources]);
            setPage(page + 1);
          })
          .catch(err => console.error('Error fetching resources: ' + err));
        setIsFetching(false);
        console.log(page);
      }
    }, 1000);
  }

这可以使用自下而上的递归方法来实现:


const [page, setPage] = useState(2);

const fetchFunction = (pageToLoad) => {

  // basecase
  if (pageToLoad === page) {
    return props.resource.follow('activity-collection');
  } else {
    return fetchFunction(pageToLoad + 1).follow('next')
  }
}

fetchFunction(0)

/// call chain for page = 2:

props.resource.follow('activity-collection').follow('next').follow('next')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM