无限滚动与Firebase 9在React Native



我正在尝试在React Native中使用Firebase 9实现无限滚动,用于评论组件。

我有一个集合叫做dailyTips,其中包含多个文档,对于每个文档,我将注释保存在名为comments的数组中。.

这是我如何获取一个文档的所有评论:

const [allComments, setAllComments] = useState([])
const getComments = async () => {
try {
setIsLoaded(false)
const docRef = doc(db, "dailyTips", id);
const unsubscribe = onSnapshot(docRef, (snapshot) => {
setAllComments(snapshot?.data().comments)
setIsLoaded(true)
})
return unsubscribe;
} catch (error) {
console.error(error)
}
}
useEffect(() => {
getComments()
}, [])

allComments获取特定文档的注释后的状态变量包含:

{
"comment": "Yep", 
"name": "Testing Account", 
"time": "", 
"user": "userIdGeneratedByFirebase"
}, 
{
"comment": "Test comment", 
"name": "Alex", 
"time": "", 
"user": "userIdGeneratedByFirebase"
},
...

这就是我如何在文档详细信息屏幕上显示每个评论(我使用map from lodash):

{map(!allComments ? allComments : allComments.sort((a, b) => b.time - a.time), (comment, i) => (
<SingleComment comment={comment} matchId={id} key={i} />
))}

是否有办法在getComments()中将查询限制为特定的数字?函数,能够只得到最后5个评论,例如,在开始?然后,查询旧的5条评论,在加载时显示ActivityIndicator,并在加载后显示它们,以实现无限滚动效果?我没有在doc中找到任何关于查询的内容。

我想我还需要移动到FlatList而不是map才能实现这一点,但我不确定从哪里开始。

这是一篇讨论在react native中使用Flatlist实现延迟加载的文章。希望这将帮助你开始你的方法。

最新更新