javascript - React hooks FlatList pagination
问题描述
I am trying to let the FlatList get 20 posts from Firestore and render 20. when the end is reached I would like to call the getPosts
method to get the next 20 posts which means I will have to have a way to save the last known cursor
. This is what I was trying to do when converting class component to hooks.
Please can someone help me , no one answered my last question about this
const Posts = (props) => {
//How to get 20 posts from firebase and then render 20 more when the end is reached
const [allPosts, setAllPosts] = useState();
const [loading, setLoading] = useState(true)
const [isRefreshing, setRefreshing] = useState(false);
useEffect(() => {
getPosts();
}, []);
const getPosts = async () => {
try {
var all = [];
const unsubscribe = await firebase
.firestore()
.collection("Posts")
.orderBy("timestamp",'desc')
.get()
.then((querySnapshot) => {
querySnapshot.docs.forEach((doc) => {
all.push(doc.data());
});
setLoading(false);
});
setAllPosts(all);
if(currentUser === null){
unsubscribe()
}
} catch (err) {
setLoading(false);
}
};
const onRefresh = useCallback(() => {
setRefreshing(true);
getPosts()
.then(() => {
setRefreshing(false);
})
.catch((error) => {
setRefreshing(false); // false isRefreshing flag for disable pull to refresh
Alert.alert("An error occured", "Please try again later");
});
}, []);
return (
<FlatList
data={allRecipes}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={onRefresh}
/>
}
initialNumToRender={20}
keyExtractor={(item, index) => item.postId}
renderItem={renderItem}
/>
);
}
解决方案
const Posts = () =>{
const [posts, setPosts] = useState();
const [data, setData] = useState();
const addPosts = posts => {
setData({...data,...posts})
// `setData` is async , use posts directly
setPosts(Object.values(posts).sort((a, b) => a.timestamp < b.timestamp))
};
}
推荐阅读
- datetime - 谷歌脚本:弄清楚如何比较时间 B 和时间 C 之间的时间 A
- javascript - 通过底部激活/停用字段(HTML + Javascript)
- python - jupyter notebook和google colaboratory之间的LSTM性能差异
- javascript - 我在使用“更改”事件时遇到问题。我能做些什么?我可以使用什么活动?
- javascript - 谷歌表格自动按颜色排序范围
- javascript - 如何在 javascript 网站中使用 OpenTripPlanner?
- hadoop - 当数据从 hive 导出到 hadoop 边缘节点上的 csv 时,记录行数增加
- node.js - express 如何在没有 next() 的异步代码中捕获抛出的错误?
- delphi - 显示在包含 tchart 的面板顶部的 tPanel 是透明的(Delphi)
- r - 没有标签或轴标题 - WaveleComp 包的 wc.image 问题(?)