(遇到的需求:使用antd Select选择器时,后端数据量非常大

类似这种:

准备的解决方法:后端数据分页,前端下拉滚动加载

用到的api:

后端接口格式:[[http://localhost:8000/es/list?pageIndex=1&pageSize=10](http://localhost:8000/es/list?pageIndex=1&pageSize=10%5C)]

 1{
 2  "code": 10000,
 3    "title": "提示",
 4      "msg": "OK",
 5        "data": {
 6          "pageIndex": 1,
 7            "pageSize": 10,
 8              "totalPage": 1,
 9                "totalRecord": 7,
10                  "pageObject": [
11                    {
12                      "id": "a10",
13                      "name": "a10"
14                    },
15                    {
16                      "id": "b11",
17                      "name": "b11"
18                    },
19                    {
20                      "id": "c12",
21                      "name": "c12"
22                    },
23                    {
24                      "id": "d13",
25                      "name": "d13"
26                    }
27                  ]
28        }
29}

前端写法:

 1const [list, setList] = useState([]);
 2const [listIndex, setListIndex] = useState(1);
 1/** 请求 */
 2const getList = async(params) => {
 3  try{
 4    const { data } = await request('es/list', {
 5      method: 'GET',
 6      params: {
 7        pageIndex: listIndex,
 8        pageSize: 10
 9      }
10    })
11
12    const newList = data?.pageObject ?? [];
13    setList(list.concat(newList));
14
15    if(data?.pageIndex == data?.totalPage) { //如果是最后一页
16      setListIndex(-1);
17    }else{
18      setListIndex(listIndex + 1)
19    }
20  }catch(e){
21    console.log(e)
22  }
23}
24
25useEffect(() => {
26  getList();
27},[])
 1/** 下拉滚动回调 */
 2const onPopupScroll = (e) => {
 3  e.persist();
 4
 5  const { scrollTop, offsetHeight, scrollHeight } = e.target;
 6
 7  if(scrollTop + offsetheight === scrollHeight) {
 8    if(listIndex != -1) {
 9      getList();
10    }
11  }
12}
 1<Select
 2style={{ width: 300 }}
 3placeholder="请选择"
 4onPopupScroll={onPopupScroll}>
 5  {list.map(item => {
 6   const { id } = item;
 7return (
 8  <Select.Option key={id} value={id}>
 9  {id}
10</Select.Option> 
11)
12})}
13  </Select>
个人笔记记录 2021 ~ 2025