select滑动分页请求数据

需求背景

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 为 pageSize
        if (current * 10 >= total) {
          allLoadedRef.current = false;
          return;
        }
    } catch {
      message.error('请求超时,请稍后再试!');
    } finally {
      setLoading(false);
    }
  };

监听 current

复制代码
 useEffect(() => {
    getList();
  }, [current]);

调用

复制代码
 <Select
  onPopupScroll={(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>
相关推荐
云水一下7 小时前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing7 小时前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
copyer_xyf7 小时前
Python 模块与包的导入导出
前端·后端·python
研☆香8 小时前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角8 小时前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
copyer_xyf8 小时前
Python venv 虚拟环境
前端·后端·python
无聊的老谢8 小时前
Vue 3 + TypeScript 构建大型电信运维平台的前端架构设计
前端·vue.js·typescript
xiaofeichaichai8 小时前
Map / Set / WeakMap / WeakSet
前端·javascript
李可以量化8 小时前
成交量的终极量化策略:价量共振指标完整实现(下篇)
前端·数据库·人工智能
copyer_xyf9 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python