触底加载
使用ant-mobile组件
npm i antd-mobile
yarn i antd-mobile
后端接口
router.get('/home', async (req, res, next) => {
// 接受长度的len
let len = req.query.len
const data = await homeModel.find().limit(len) //限制的条数
let lens = (await homeModel.find()).length //总条数
if (lens > len) { //条数在限定范围内
res.send({ code: 200, data, hasMore: true }) //hasMore判断是否有数据
} else {
res.send({ code: 200, data, hasMore: false })
}
});
前段react框架
import React, { useEffect, useState } from 'react'
import '../assets/css/index.scss'
import axios from '../utils/index'
import { InfiniteScroll } from 'antd-mobile'
import { sleep } from 'antd-mobile/es/utils/sleep'
export default function Index() {
const [list, setList] = useState([]) //获取数据
const [len, setlen] = useState(3) //条数
const [hasMore, sethasMore] = useState(true) //状态
const getHome = async () => {
//传递条数
const { data } = await axios.get(`home?len=${len}`)
if (data.hasMore) {
setlen(len + 2)
}
sethasMore(data.hasMore)
setList(data.data)
}
const loadMore = async () => {
await sleep(2000)
getHome()
}
useEffect(() => {
getHome()
}, [])
return (
<div>
<ul>
{list.map(item =>
<li key={item._id}>
<img src={require('../assets/images/' + `${item.img}`)} alt="" style={{ width: "160px" }} />
<p>{item.name}</p>
</li>
)}
</ul>
<InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
</div>
)
}