React native how to apply pagination and loadmore to each specific tab separately?

核能气质少年 提交于 2021-01-07 01:14:00

问题


so i currently have a screen with a horizontal scroll view that contains my category tabs. When a tab is pressed, a flatlist is rendered below with all the posts specific for that category (this part is working correctly).

When the screen initially loads the first tab is selected by default and all the posts for that tab are rendered below.

Now, i have applied pagination in my backend and when i tested it on postman it is working.

My problem is:

eg. if i select tab 1, the first page (page=0) posts get rendered then when i scroll down, the page count increases to 2 but no posts get rendered. Also, then when i select tab 2, the page count doesnt reset back 0 it continues from where it left off in tab 1.

in tab 1 if i keep scrolling down to page 10, then i select tab 2.

What i want is the page count in tab 2 to start at 0.

what is happening the page count in tab 2 starts at 10.

Here is my code:

const getCategoryPostsAPI = (id,page)=>client.get(`/categories/${id}?page=${page}`)

function tabScreen({ navigation,route }) {
const [posts, setPosts] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const[page,setPage]=useState(0);

const loadPosts = async (id) => {
setLoading(true);
const response = await getCategoryPostsAPI(id,page) //API call
setLoading(false);

if(refreshing) setRefreshing(false);
if (!response.ok) return setError(true);
setError(false);

if(page===0){
  setPosts(response.data)
}else{    
setPosts([...posts,...response.data]);
}};

useEffect(() => {
loadPosts(1,page);
}, [page]);

const categories = [
{
label: "Sports",
id: 1,
},
{
label: "Fashion",
id: 2,
},
{
label: "News",
id: 3,
},
{
label: "Cooking",
id: 4,
},
{
label: "Education",
id: 5,
}]

const handleLoadMore = ()=>{
setPage(page+1);
}

const[label,setLabel]=useState('Sports')

const setLabelFilter=label=>{
setLabel(label)
}

const [currentCategoryId, setCurrentCategoryId] = useState()

const toggleBrands = (categoryId) => {
setCurrentCategoryId(categoryId)
setLabel(label)
};

return (

<ScrollView 
horizontal 
showsHorizontalScrollIndicator={false}
>
{categories.map(e=>(
        <TouchableOpacity 
            key={e.id}
            onPress={()=>{toggleBrands(e.id),
                          setLabelFilter(e.label),
                          loadPosts(id=e.id),                        
                          setPage(0) // here i am trying to set the page to 0 on tab click 
                                        but it is not working
                          }}
            selected={e.id === currentCategoryId}
            >
        <Text>{e.label}</Text>
        </TouchableOpacity>
))}
</ScrollView>

<FlatList
  data={currentCategoryId ? posts.filter(post=>post.categoryId===currentCategoryId
    ):posts.filter(post=>post.categoryId===1)} 
  keyExtractor={(post) => post.id.toString()}
  renderItem={({ item,index }) => (
   <Card
      title={item.title}
      subTitle={item.subTitle}
      onPress={() => navigation.navigate(routes.POST_DETAILS, {post:item,index})}
    />
      onEndReached={handleLoadMore}
      onEndReachedThreshold={0.000001}
      initialNumToRender={10}
  )}
/>

I think i implemented my pagination wrong hence why my handleloadmore does not work because i have used the same handleloadmore in different screens and it is working.


回答1:


I'm guessing you want the page to be reset to 0 when you click on another category and you want to paginate through the data when scrolling through a single category. If so, try this

const getCategoryPostsAPI = (id, page) => client.get(`/categories/${id}?page=${page}`);

const categories = [
  {
    label: "Sports",
    id: 1,
  },
  {
    label: "Fashion",
    id: 2,
  },
  {
    label: "News",
    id: 3,
  },
  {
    label: "Cooking",
    id: 4,
  },
  {
    label: "Education",
    id: 5,
  }
];

function tabScreen({ navigation, route }) {
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(0);
  const [label, setLabel] = useState(categories[0]?.label);
  const [currentCategoryId, setCurrentCategoryId] = useState(1);

  const loadPosts = async (id, page = 0) => {
    setLoading(true);
    const response = await getCategoryPostsAPI(id, page)
    setLoading(false);
    if (refreshing) setRefreshing(false);
    if (!response.ok) return setError(true);
    setError(false);
    if (page === 0) {
      setPosts(response.data)
    } else {
      setPosts([...posts, ...response.data]);
    }
  };

  useEffect(() => {
    if (page > 0)
      loadPosts(currentCategoryId, page);
  }, [page]);

  useEffect(() => {
    setPage(0);
    loadPosts(currentCategoryId, 0);
  }, [currentCategoryId])

  const handleLoadMore = () => {
    setPage(page + 1);
  };

  const setLabelFilter = label => {
    setLabel(label);
  };

  const toggleBrands = (categoryId) => {
    setCurrentCategoryId(categoryId);
  };

  const postsToBeDisplayed = () => posts.filter(post => post.categoryId === currentCategoryId);

  return (
    <>
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
      >
        {categories.map(e => (
          <TouchableOpacity
            key={e.id}
            onPress={() => {
              toggleBrands(e.id);
              setLabelFilter(e.label);
            }}
            selected={e.id === currentCategoryId}
          >
            <Text>{e.label}</Text>
          </TouchableOpacity>
        ))}
      </ScrollView>

      <FlatList
        data={postsToBeDisplayed()}
        renderItem={({ item, index }) => (
          <Card
            title={item.title}
            subTitle={item.subTitle}
            onPress={() => navigation.navigate(routes.POST_DETAILS, { post: item, index })}
          />
        )}
        onEndReached={handleLoadMore}
        onEndReachedThreshold={0.000001}
        initialNumToRender={10}
        keyExtractor={(post) => post.id.toString()}
      />
    </>
  )
};


However, if you want to implement the tab feature, I would recommend using react-native-tab-view. This will make the whole process a lot easier.



来源:https://stackoverflow.com/questions/65109567/react-native-how-to-apply-pagination-and-loadmore-to-each-specific-tab-separatel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!