#鸿蒙通关秘籍#怎样实现 HarmonyOS Next 中触底加载并结合节流功能?

HarmonyOS
2024-11-28 14:53:52
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
CodeNinja

通过在 HarmonyOS Next 中引入布尔变量以确保触底请求节流,具体步骤如下:

import  LoadingMoreView from '../components/LoadingMoreView';

@Entry
@Component
struct ListPage {
  @State list: number[] = [];
  private pageSize: number = 10;
  private pageNo: number = 1;
  @State  reachStatus: number = 0;
  private isLoadingMore: boolean = false;
  private initCompleted: boolean = false;
  @State loadingMoreVisible: boolean = false;

  aboutToAppear(): void {
    this.init();
  }

  async init() {
    try {
      this.list = await this.getList(1);
    } catch (e) {
    } finally {
      this.initCompleted = true;
    }
  }

  getList(pageNo: number): Promise<Array<number>> {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (pageNo < 4) {
          let newData: number[] = [];
          for (let i = (pageNo - 1) * this.pageSize; i < pageNo * this.pageSize; i++) {
            newData.push(i);
          }
          resolve(newData);
        } else {
          resolve([]);
        }
      }, 1000);
    });
  }

  async handleLoadingMore() {
    if (this.isLoadingMore) {
      return;
    }
    this.isLoadingMore = true;
    this.reachStatus = 1;

    let pageNo = this.pageNo + 1;
    try {
      let data = await this.getList(pageNo);
      if (data && data.length > 0) {
        setTimeout(() => {
          this.list = [...this.list, ...data];
          this.pageNo += 1;
          this.isLoadingMore = false;
          this.reachStatus = 0;
        }, 500);
      } else {
        this.isLoadingMore = false;
        this.reachStatus = 2;
      }
    } catch (e) {
      this.isLoadingMore = false;
    }
  }

  build() {
    List({ space: 20 }) {
      ForEach(this.list, (item: number) => {
        ListItem() {
          Text(item.toString());
        }.width('100%').height(90).backgroundColor('#fff').borderRadius(10);
      }, (item: number) => item.toString());

      LoadingMoreView({visible: this.loadingMoreVisible, status: this.reachStatus});
    }
    .height('100%')
    .width('100%')
    .padding(20)
    .backgroundColor('#f2f2f2')
    .onReachEnd(() => {
      if (this.initCompleted && this.reachStatus !== 2) {
        this.loadingMoreVisible = true;
        this.handleLoadingMore();
      }
    });
  }
}

通过 isLoadingMore 来阻止在数据请求完成之前重复发送请求,从而实现节流,代码中 handleLoadingMore 函数保证每次只发出一个请求。

分享
微博
QQ
微信
回复
2024-11-28 16:32:55
相关问题