首页 > 解决方案 > 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}
      />
  );
}

标签: javascriptfirebasereact-nativereact-hooks

解决方案


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))
  };
}


推荐阅读