1# WaterFlow高性能开发指导
2
3## 背景
4
5瀑布流常用于展示图片信息,如多用于购物、资讯类应用。下面通过对[WaterFlow](../reference/apis-arkui/arkui-ts/ts-container-waterflow.md)组件示例代码的逐步改造,介绍优化WaterFlow性能的方法。
6
7## 使用懒加载
8
9先看一下组件示例代码中瀑布流的基本用法:
10
11```ts
12  build() {
13    Column({ space: 2 }) {
14      WaterFlow() {
15        LazyForEach(this.dataSource, (item: number) => {
16          FlowItem() {
17            Column() {
18              Text("N" + item).fontSize(12).height('16')
19              Image('res/waterFlowTest (' + item % 5 + ').jpg')
20                .objectFit(ImageFit.Fill)
21                .width('100%')
22                .layoutWeight(1)
23            }
24          }
25          .width('100%')
26          // 提前设定FlowItem高度,避免自适应图片高度
27          .height(this.itemHeightArray[item])
28          .backgroundColor(this.colors[item % 5])
29        }, (item: string) => item)
30      }
31      .columnsTemplate("1fr 1fr")
32      .columnsGap(10)
33      .rowsGap(5)
34      .backgroundColor(0xFAEEE0)
35      .width('100%')
36      .height('80%')
37    }
38  }
39```
40
41示例代码已经使用了[LazyForEach](../quick-start/arkts-rendering-control-lazyforeach.md)进行数据懒加载,WaterFlow布局时会根据可视区域按需创建FlowItem组件,并在FlowItem滑出可视区域外时销毁以降低内存占用。
42
43另外,由于Image组件默认异步加载,建议提前根据图片大小设定FlowItem的高度,避免图片加载成功后高度变化触发瀑布流刷新布局。
44
45## 无限滚动
46
47示例代码中FlowItem数量是固定的,不能满足无限滚动的场景。
48
49基于WaterFlow本身提供的能力,可以在onReachEnd时给LazyForEach数据源增加新数据,并将footer做成正在加载新数据的样式(使用[LoadingProgress](../reference/apis-arkui/arkui-ts/ts-basic-components-loadingprogress.md)组件)。
50
51```ts
52  build() {
53    Column({ space: 2 }) {
54      WaterFlow({ footer: this.itemFoot.bind(this) }) {
55        LazyForEach(this.dataSource, (item: number) => {
56          FlowItem() {
57            Column() {
58              Text("N" + item).fontSize(12).height('16')
59              Image('res/waterFlowTest (' + item % 5 + ').jpg')
60                .objectFit(ImageFit.Fill)
61                .width('100%')
62                .layoutWeight(1)
63            }
64          }
65          .width('100%')
66          .height(this.itemHeightArray[item % 100])
67          .backgroundColor(this.colors[item % 5])
68        }, (item: string) => item)
69      }
70      // 触底加载数据
71      .onReachEnd(() => {
72        console.info("onReachEnd")
73        setTimeout(() => {
74          this.dataSource.addNewItems(100)
75        }, 1000)
76      })
77      .columnsTemplate("1fr 1fr")
78      .columnsGap(10)
79      .rowsGap(5)
80      .backgroundColor(0xFAEEE0)
81      .width('100%')
82      .height('80%')
83    }
84  }
85
86  // 在数据尾部增加count个元素
87  public addNewItems(count: number): void {
88    let len = this.dataArray.length
89    for (let i = 0; i < count; i++) {
90      this.dataArray.push(this.dataArray.length)
91    }
92    this.notifyDatasetChange([{ type: DataOperationType.ADD, index: len, count: count }]);
93  }
94```
95
96此处需要通过在尾部增加元素的方式新增数据,不能使用直接修改dataArray后通过LazyForEach的onDataReloaded()通知瀑布流重新加载数据。
97
98由于瀑布流布局子组件高度不相等的特点,下面节点的位置依赖上面的节点,重新加载所有数据会触发整个瀑布流重新计算布局导致卡顿。而在数据末尾增加数据后使用notifyDatasetChange([{ type: DataOperationType.ADD, index: len, count: count }])通知,瀑布流就知道有新增数据可以继续加载,同时又不会重复处理已有数据。
99
100![](figures/waterflow-perf-demo1.gif)
101
102## 提前新增数据
103
104虽然在onReachEnd()触发时新增数据可以实现无限加载,但在滑动到底部时,会有明显的停顿加载新数据的过程。
105
106想要流畅的进行无限滑动,还需要调整下增加新数据的时机。比如可以在LazyForEach还剩若干个数据就迭代到结束的情况下提前增加一些新数据。
107
108```ts
109  build() {
110    Column({ space: 2 }) {
111      WaterFlow() {
112        LazyForEach(this.dataSource, (item: number) => {
113          FlowItem() {
114            Column() {
115              Text("N" + item).fontSize(12).height('16')
116              Image('res/waterFlowTest (' + item % 5 + ').jpg')
117                .objectFit(ImageFit.Fill)
118                .width('100%')
119                .layoutWeight(1)
120            }
121          }
122          .onAppear(() => {
123            // 即将触底时提前增加数据
124            if (item + 20 == this.dataSource.totalCount()) {
125              this.dataSource.addNewItems(100)
126            }
127          })
128          .width('100%')
129          .height(this.itemHeightArray[item % 100])
130          .backgroundColor(this.colors[item % 5])
131        }, (item: string) => item)
132      }
133      .columnsTemplate("1fr 1fr")
134      .columnsGap(10)
135      .rowsGap(5)
136      .backgroundColor(0xFAEEE0)
137      .width('100%')
138      .height('80%')
139    }
140  }
141```
142
143此处通过在FlowItem的onAppear中判断距离数据终点的数量,提前增加数据的方式实现了无停顿的无限滚动。
144
145![](figures/waterflow-perf-demo2.gif)
146
147## 组件复用
148
149现在,得到了一个无限滚动且没有显式等待加载的瀑布流,还能不能进一步优化性能呢?
150
151考虑到滑动场景存在FlowItem及其子组件的频繁创建和销毁,可以将FlowItem中的组件封装成自定义组件,并使用@Reusable装饰器修饰,使其具备组件复用能力,减少ArkUI框架内部反复创建销毁节点的开销。组件复用的详细介绍可以参考[组件复用最佳实践](component-recycle.md)。
152
153```ts
154  build() {
155    Column({ space: 2 }) {
156      WaterFlow() {
157        LazyForEach(this.dataSource, (item: number) => {
158          FlowItem() {
159            // 使用可复用自定义组件
160            ResuableFlowItem({ item: item })
161          }
162          .onAppear(() => {
163            // 即将触底时提前增加数据
164            if (item + 20 == this.dataSource.totalCount()) {
165              this.dataSource.addNewItems(100)
166            }
167          })
168          .width('100%')
169          .height(this.itemHeightArray[item % 100])
170          .backgroundColor(this.colors[item % 5])
171        }, (item: string) => item)
172      }
173      .columnsTemplate("1fr 1fr")
174      .columnsGap(10)
175      .rowsGap(5)
176      .backgroundColor(0xFAEEE0)
177      .width('100%')
178      .height('80%')
179    }
180  }
181@Reusable
182@Component
183struct ResuableFlowItem {
184  @State item: number = 0
185
186  // 从复用缓存中加入到组件树之前调用,可在此处更新组件的状态变量以展示正确的内容
187  aboutToReuse(params) {
188    this.item = params.item;
189  }
190
191  build() {
192    Column() {
193      Text("N" + this.item).fontSize(12).height('16')
194      Image('res/waterFlowTest (' + this.item % 5 + ').jpg')
195        .objectFit(ImageFit.Fill)
196        .width('100%')
197        .layoutWeight(1)
198    }
199  }
200}
201
202```
203
204## 总结
205
206WaterFlow配合LazyForEach渲染控制语法、提前加载数据和组件复用可以达到无限滚动场景性能最优效果。
207