原理解析:每滚动一次相当于翻页,请求后端时给的页码参数要想办法加1,后端才能根据页码给出相应数据
注意后端收到页码参数之后要准确计算出每页的首行数据,关键逻辑代码:
# 根据前端传的页码,进行计算下一页的起始行号 page = (int(params['page'])-1)*10+1 sql = f"SELECT * FROM dong_c_di_comment limit 10 offset {page}" print(sql)
前端实现部分:
const [loading, setLoading] = useState(false); const [data, setData] = useState([]); // 定义传给后端的页码钩子 const [page, setPage] = useState(1); const loadMoreData = async () => { if (loading) { return; } setLoading(true); const params = {page:page} get_cars(params) .then(res => { setData([...data, ...res.data]); setPage(page + 1); setLoading(false); }) .catch(() => { setLoading(false); }); }; useEffect(() => { loadMoreData(); }, []);
return( <div id="scrollableDiv" style={{ width:"350px", height: "900px", overflow: 'auto', padding: '0 16px', border: '1px solid rgba(140, 140, 140, 0.35)', }} > <InfiniteScroll dataLength={data.length} next={loadMoreData} hasMore={data.length < 50} loader={<Skeleton avatar paragraph={{ rows: 1 }} active />} endMessage={<Divider plain>加载完毕, 没有更多数据了哦 🤐</Divider>} scrollableTarget="scrollableDiv" > <List dataSource={data} renderItem={(item) => { // console.log("item1111111",item) return ( <List.Item key={item.commenter_name}> <List.Item.Meta avatar={<Avatar src={item.avatar_url} />} title={<a href="https://ant.design">{item.title}</a>} description={item.content} /> </List.Item> ) } } /> </InfiniteScroll> </div> )