本文介绍了React Native 如何分别将分页和加载更多应用于每个特定选项卡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我目前有一个带有水平滚动视图的屏幕,其中包含我的类别选项卡.当一个选项卡被按下时,下面会呈现一个平面列表,其中包含该类别特定的所有帖子(这部分工作正常).

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.

我的问题是:

例如.如果我选择选项卡 1,则呈现第一页 (page=0) 帖子,然后当我向下滚动时,页数增加到 2,但没有呈现任何帖子.此外,当我选择选项卡 2 时,页数不会重置为 0,而是从它在选项卡 1 中停止的位置继续.

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.

在选项卡 1 中,如果我继续向下滚动到第 10 页,则选择选项卡 2.

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

我想要的是标签 2 中的页数从 0 开始.

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

标签 2 中的页数从 10 开始.

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

这是我的代码:

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

我想我实现了我的分页错误,因此为什么我的 handleloadmore 不起作用,因为我在不同的屏幕上使用了相同的 handleloadmore 并且它正在工作.

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.

推荐答案

我猜您希望在单击另一个类别时将页面重置为 0,并且您希望在滚动浏览单个类别时对数据进行分页.如果是这样,试试这个

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


然而,如果你想实现标签功能,我会推荐使用 react-native-tab-view.这将使整个过程变得容易很多.

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.

这篇关于React Native 如何分别将分页和加载更多应用于每个特定选项卡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 12:25