我正在尝试实现产品列表的延迟加载。我已经模拟了对服务器的异步请求。即使项目结束,用户也应该能够通过滚动来更新页面 问题是当加载元素消失时,它执行handleScroll()处理程序,因为页面的高度发生了变化,无限循环开始。但是我只想在用户滚动页面时才执行handleScroll() 这是我的组件的代码:
import React from 'react';
import './items-list.css';
import ItemsListItem from './items-list-item.jsx';
export default class ItemsList extends React.Component {
constructor(props) {
super(props);
this.state = {
categoryId: this.props.categoryId,
items: [],
isLoading: true
}
}
componentDidMount(){
window.addEventListener('scroll', this.handleScroll());
this.simulateAsyncGetItems(10);
}
componentWillUnmount(){
window.removeEventListener('scroll', this.handleScroll());
}
simulateAsyncGetItems(n){//TODO: delete in prod
this.setState({
isLoading: true
});
setTimeout(() => {
let res = this.getItems(this.props.categoryId, n, this.state.items.length);
this.setState({
items: [...this.state.items, ...res],
isLoading: false
});
}, 1000);
}
getItems(categoryId, limit, offset){
//TODO: implement request to fetch data from server
if(offset >= 20) {
return []
}
return categoryId === -1 ? [] : new Array(limit).fill(
{
id: 12345678,
categoryId: categoryId,
name: "Product name might be long",
img: "boat.jpg",
price: 1111.11
});//dummy
}
handleScroll(){
return (event) => {
let relativeScrollOffset = //scroll offset from 0.0 to 1.0
event.srcElement.scrollingElement.scrollTop /
(event.srcElement.scrollingElement.scrollHeight - event.srcElement.scrollingElement.clientHeight);
if (!this.state.isLoading && !this.state.noMoreData && relativeScrollOffset >= 0.9)
this.simulateAsyncGetItems(5);
}
}
render() {
return(
<div className="items-list" >
{(this.state.items && Array.isArray(this.state.items)) && this.state.items.map((item, i) =>
<ItemsListItem
id={item.id}
img={item.img}
name={item.name}
price={item.price}
key={i}
/>
)}
{this.state.isLoading&&
<div>
Data is loading, please wait...
</div>
}
</div>
);
}
}
答案 0 :(得分:0)
我没有解决问题,只为没有装载时空元素设置固定高度