react pc端下拉加载

7 篇文章 0 订阅
import React from 'react'
import {article} from '../../api'
import './index.scss'
import debounce from 'lodash/debounce';

export default class Index extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            result: [],
            dropItemPage: 1
        };
        this.handleDropArticle = debounce(this.handleDropArticle, 500, {leading: true, trailing: false});
    }

    componentDidMount() {
        this.getDropArticle(this.state.dropItemPage)
        window.addEventListener('scroll', this.handleScroll)
    }

    getDropArticle(page) {
        article.category_article({
            page: page
        }).then(res => {
            if(res.data.length ==0){
                alert('没有数据');
                window.removeEventListener('scroll', this.handleScroll)
                return false
            }
            this.setState({
                result: this.state.result.concat(res.data)
            })
        })
    }

    handleDropArticle() {
        return this.getDropArticle(++this.state.dropItemPage)
    }

    handleScroll = () => {
        let isScrollBottom = (parseInt(this.getScrollTop()) + parseInt(this.getClientHeight())) - parseInt(this.getScrollHeight())
        if (isScrollBottom === 0 || isScrollBottom === 1) {
            this.handleDropArticle()
        }
    }

    getScrollTop() {
        var scrollTop = 0;
        if (document.documentElement && document.documentElement.scrollTop) {
            scrollTop = document.documentElement.scrollTop;
        } else if (document.body) {
            scrollTop = document.body.scrollTop;
        }
        return scrollTop;
    }

    getClientHeight() {
        var clientHeight = 0;
        if (document.body.clientHeight && document.documentElement.clientHeight) {
            clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
        } else {
            clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
        }
        return clientHeight;
    }

    getScrollHeight() {
        return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    }

    render() {
        return (
            <div className='Index__container'>
                <div className="dorp__column">
                    {this.state.result.map((item, index) => (
                        <div key={index} className="column__item">
                            {item.title}
                        </div>
                    ))}
                </div>
            </div>
        );
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值