(遇到的需求:使用antd Select选择器时,后端数据量非常大
类似这种:
准备的解决方法:后端数据分页,前端下拉滚动加载
用到的api:
后端接口格式:[http://localhost:8000/es/list?pageIndex=1&pageSize=10]
{
"code": 10000,
"title": "提示",
"msg": "OK",
"data": {
"pageIndex": 1,
"pageSize": 10,
"totalPage": 1,
"totalRecord": 7,
"pageObject": [
{
"id": "a10",
"name": "a10"
},
{
"id": "b11",
"name": "b11"
},
{
"id": "c12",
"name": "c12"
},
{
"id": "d13",
"name": "d13"
}
...
]
}
}
前端写法:
const [list, setList] = useState([]);
const [listIndex, setListIndex] = useState(1);
/** 请求 */
const getList = async(params) => {
try{
const { data } = await request('es/list', {
method: 'GET',
params: {
pageIndex: listIndex,
pageSize: 10
}
})
const newList = data?.pageObject ?? [];
setList(list.concat(newList));
if(data?.pageIndex == data?.totalPage) { //如果是最后一页
setListIndex(-1);
}else{
setListIndex(listIndex + 1)
}
}catch(e){
console.log(e)
}
}
useEffect(() => {
getList();
},[])
/** 下拉滚动回调 */
const onPopupScroll = (e) => {
e.persist();
const { scrollTop, offsetHeight, scrollHeight } = e.target;
if(scrollTop + offsetheight === scrollHeight) {
if(listIndex != -1) {
getList();
}
}
}
<Select
style={{ width: 300 }}
placeholder="请选择"
onPopupScroll={onPopupScroll}>
{list.map(item => {
const { id } = item;
return (
<Select.Option key={id} value={id}>
{id}
</Select.Option>
)
})}
</Select>