我想通过触发滚动事件来加载更多数据,但它不起作用。
代码:
const CardPage = function (props) {
const [data, setData] = useState([]);
const [from, setSize] = useState(1);
const size = 10;
function fetchData () {
const suv = window.localStorage.getItem("suv") || "gligli-user";
const requestId = suv + (+Date.now());
const url = baseUrl + "/api/mainpage" + "/fetch/card";
axios.get(url, {
params: {
requestId,
size,
from
}
}).then((res) => {
const curData = [...data, ...res.data];
//the data is always an empty array
console.log(data, res.data);
setData(curData);
setSize(from + size);
})
}
useEffect(() => {
fetchData();
window.onscroll = function() {
const windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
const scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
const $cardWrap = document.getElementById("card-page-wrap");
const domHeight = +window.getComputedStyle($cardWrap).height.match(/[0-9]*/)[0];
if ((windowHeight + scrollTop) - domHeight < -20) {
fetchData();
}
};
}, [])
return (<Fragment>
<div className="card-page-wrap" id="card-page-wrap">
<ul>
{
data.map((item) => {
return (<li><img src={item.imgSrc} alt="gligli-img" onClick={(event) => { showPicture(event) }}/></li>)
})
}
</ul>
</div>
</Fragment>)
}
console
打印的结果如下:
[] (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
[] (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
每次,数据总是一个空数组。
尝试使用async/await
,让我知道它是否解决了您的问题。您的服务器正在返回一个非空对象?
const fetchData=async()=>{
//your existing code
try{
const res = await axios.get(url, {
params: {
requestId,
size,
from
}
});
const curData = [...data, ...res.data];
setData(curData);
setSize(from + size);
} catch(err){
console.log(err);
}
}