目录

下拉刷新列表,部分数据无变化

问题现象

列表每次下拉刷新,只刷新了前两条内容,第三条内容无变化。

背景知识

问题定位

列表下拉刷新后,前两条成功刷新,则获取后端信息逻辑正确,需排查如下两点:

数据更新错误示例代码:

代码遍历了获取到的数据源,但存在更新不完全,以及新数据过多,数组越界问题。

.onRefreshing(() => {
  let listData: String[] = []
  // 模拟数据获取
  setTimeout(() =>{
    listData = ['1-1', '1-2']
  }, 1000)
  setTimeout(() => {
    this.isRefreshing = false;
    listData.forEach((data, index) => {
      this.arr[index] = data
    })
  }, 2000)
})

分析结论

修改建议

示例代码:

@Entry
@Component
struct RefreshExample {
  @State isRefreshing: boolean = false;
  @State arr: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

  build() {
    Column() {
      Row({ space: 35 }) {
        Button('开始刷新').onClick(() => {
          this.isRefreshing = true;
        });
        Button('停止刷新').onClick(() => {
          this.isRefreshing = false;
        });
      }.padding({ top: 10, bottom: 20 });

      Refresh({ refreshing: $$this.isRefreshing }) {
        List({ space: 10 }) {
          ForEach(this.arr, (item: string) => {
            ListItem() {
              Text('' + item)
                .width('100%')
                .height(80)
                .fontSize(16)
                .textAlign(TextAlign.Center)
                .borderRadius(10)
                .backgroundColor(0xFFFFFF);
            };
          }, (item: string) => item);
        }
        .onScrollIndex((first: number) => {
          console.info(first.toString());
        })
        .width('100%')
        .padding(16)
        .height('100%')
        .alignListItem(ListItemAlign.Center)
        .scrollBar(BarState.Off);
      }
      .onStateChange((refreshStatus: RefreshStatus) => {
        console.info('Refresh onStatueChange state is ' + refreshStatus);
      })
      .onOffsetChange((value: number) => {
        console.info('Refresh onOffsetChange offset:' + value);
      })
      .onRefreshing(() => {
        // 防止数据获取失败后页面无数据
        let listData: String[] = this.arr;
        // 模拟数据获取
        setTimeout(() => {
          listData = ['1-1', '1-2'];
        }, 1000);
        // 刷新
        setTimeout(() => {
          this.isRefreshing = false;
          this.arr = listData;
        }, 2000);
      })
      .backgroundColor('#F1F3F5')
      .padding({ bottom: 50 })
      .refreshOffset(64)
      .pullToRefresh(true);
    };
  }
}