需求背景
Antd 的 select 组件支滑动分页获取后端数据
实现滑动加载数据
定义变量
const allLoadedRef = useRef<boolean>(true); // 是否触底
const [current, setCurrent] = useState<number>(1); // 当前页
const [list, setList] = useState([]); // 列表
定义方法
const getList = async () => {try {setLoading(true);// pageSize 最大 100,让用户感知不到 分页请求数据// 调用接口// 成功// 结构出后端返回给你的 total,赋值totalRef.current = total;// 10 为 pageSizeif (current * 10 >= total) {allLoadedRef.current = false;return;}} catch {message.error('请求超时,请稍后再试!');} finally {setLoading(false);}};
监听 current
useEffect(() => {getList();}, [current]);
调用
<SelectonPopupScroll={(e) => {const { target } = e;// clientHeight:客户可见的浏览器显示页面的高度。// scrollTop:滚动条的滑块距离浏览器页面最顶部的距离,即滚动条滑动了多少距离。// scrollHeight:返回元素的完整的高度const { clientHeight, scrollTop, scrollHeight } = target as any;if (clientHeight + parseInt(scrollTop) === scrollHeight) {//表示触底if (allLoadedRef.current) setCurrent((op) => op + 1);}}}onChange={onChange}>//遍历渲染 <Select.Option/></Select>