关于React.js和Material_ui中的无限滚动

问题描述 投票:0回答:1

我正在使用react.js在项目中

对于该项目,我应该包括具有无限滚动的面板,例如Facebook

因此,我有一个问题。

[当我滚动面板并回想起Facebook之类的更多帖子时,它是否正常工作

是否仅在帖子底部绘制其他帖子,或

它会调出整个列表并重新绘制它

ex) case 1 :  {1,2,3} > scroll > {1,2,3} + {4,5} (additional posts)
    case 2 :  {1,2,3} > scroll > {1,2,3,4,5} (whole posts)

如果我做案例1,我想知道如何做。

谢谢!

javascript reactjs material-ui infinite-scroll
1个回答
0
投票

您绝对应该首选第一种方法。当您从api提取数据时,它将使您具有较小的有效负载大小,并通常提供更流畅的用户体验。

假设您的api已经为您提供了一种在特定索引范围内获取posts的方法,例如https://myapi.com/posts?start=0&end=10将为您返回10条第一篇文章的列表。

然后在React.js -app中,应跟踪获取的最新索引,并在到达页面末尾时添加到索引并获取更多帖子。我在此处粘贴了用于实现此功能的块的简约代码库,演示在CodeSandbox

// Store current index of posts
const [startIndex, setStartIndex] = React.useState(0);

const LoadMorePosts = () => {
  // Load 10 more
  setStartIndex(prev => prev + 10);
};

React.useEffect(() => {
  (async () => {
    // Add search range to url
    const url = `?start=${startIndex}&end=${startIndex + 10}`;
    const posts = await mockApi(url);
    // Append new posts to end of old ones
    setPosts(prev => [...prev, ...posts]);
  })();
}, [startIndex]); // Run this effect when startIndex changes
© www.soinside.com 2019 - 2024. All rights reserved.