懒加载react-H5

本文讲述了如何在H5移动端项目中使用懒加载模式对表格数据进行展示,基于Antd库进行了定制开发,包括useState管理状态、fetchData获取数据、loadMoreData加载更多数据以及onScroll事件处理。作者还提到了使用原生JS替代的可能性和对Antd提供移动端表格组件的期望。
摘要由CSDN通过智能技术生成

因为项目需要运用到懒加载模式
但又是需要在h5移动端进行表格展示,在网上查了一圈,发现没有太多的内容进行参考,只能在antd的基础上进行改动添加

const Index = () => {
const [dataSource, setDataSource] = useState([]); // 初始化数据源
const [currentPage, setCurrentPage] = useState(0); // 初始化当前页码
const [hasMoreData, setHasMoreData] = useState(true); // 是否还有更多数据需要加载
const columns = [
{
title: ‘序号’,
width: ‘19%’,
align: ‘center’,
render: (_, key, index) => {
return

{index + 1}
;
},
},
{
title: ‘小区名称’,
dataIndex: ‘residenceDistrictName’,
width: ‘30%’,
align: ‘center’,
},
{
title: ‘业主名称’,
dataIndex: ‘ownerName’,
width: ‘30%’,
align: ‘center’,
},
{
title: ‘详情’,
width: ‘21%’,
align: ‘center’,
render: (text, record) => (
<Link to={{ you url}}>详情
),
},
];

const fetchData = async (page) => {
try {
const response = await fetch(apiurl, {
method: ‘GET’,
headers: {
Authorization: session.getToken(),
},
});
if (!response.ok) throw new Error(‘Network response was not ok’);

  const data = await response.json();
  return data.data.list;
} catch (error) {
  console.log('Error', error);
  return [];
}

};

// 根据当前页码加载新的数据
const loadMoreData = async () => {
if (!hasMoreData) {
console.log(‘已加载完所有数据’);
return;
}
const nextPage = currentPage + 1;
const newData = await fetchData(nextPage);
if (dataSource.length >= total) {
setHasMoreData(false); // 没有更多数据可加载
return;
}
setDataSource([…dataSource, …newData]);
setCurrentPage(nextPage);
};
// 加载初始数据
useEffect(() => {
loadMoreData(); // 继续加载更多数据
}, []);

// onScroll事件处理函数

const useDebounce=(func, delay)=> {
let timer;
return function (…args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}

const handleOnScroll = useDebounce(({ target }) => {
const { scrollTop, clientHeight, scrollHeight } = target;
// 判断是否接近底部,并且不是正在加载数据
if (scrollTop + clientHeight >= scrollHeight - 1) {
loadMoreData();
}
}, 1000);
return (



<div
className={styles.customTableText}
style={{ height: 580 }}
onScroll={handleOnScroll}
>
// 这一块是添加固定表头,如果你能结合ref去监听react table组件,也可以不写这一块代码,转而去用监听到的属性进行设置,暂时还没有想法去弄。。。。

<span style={{ width: ‘19%’ }}>序号
<span style={{ width: ‘30%’ }}>小区名称
<span style={{ width: ‘30%’ }}>业主名称
<span style={{ width: ‘21%’ }}>详情





);
};
export default Index;

小结

// 实在不行,其实还是可以用原生js去写这个需求的,就是代码量会比较大,比较杂,最后还是希望antdM 能够加一个移动端的表格组件吧

例如:

提供先进的推理,复杂的指令,更多的创造力。

  • 15
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值