1
我試圖實現產品列表的延遲加載。我模擬了對服務器的異步請求。即使項目結束,用戶也應該能夠通過滾動來更新頁面。
問題是當加載元素消失時,它執行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>
);
}
}