• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ForEach:循环渲染
2
3
4ForEach接口基于数组类型数据来进行循环渲染,需要与容器组件配合使用,且接口返回的组件应当是允许包含在ForEach父容器组件中的子组件。例如,ListItem组件要求ForEach的父容器组件必须为[List组件](../reference/arkui-ts/ts-container-list.md)。
5
6> **说明:**
7>
8> 从API version 9开始,该接口支持在ArkTS卡片中使用。
9
10## 接口描述
11
12
13```ts
14ForEach(
15  arr: Array,
16  itemGenerator: (item: any, index: number) => void,
17  keyGenerator?: (item: any, index: number) => string
18)
19```
20
21以下是参数的详细说明:
22
23| 参数名        | 参数类型                                | 是否必填 | 参数描述                                                     |
24| ------------- | --------------------------------------- | -------- | ------------------------------------------------------------ |
25| arr           | Array<any>                                   | 是       | 数据源,为`Array`类型的数组。<br/>**说明:**<br/>- 可以设置为空数组,此时不会创建子组件。<br/>- 可以设置返回值为数组类型的函数,例如`arr.slice(1, 3)`,但设置的函数不应改变包括数组本身在内的任何状态变量,例如不应使用`Array.splice()`,`Array.sort()`或`Array.reverse()`这些会改变原数组的函数。 |
26| itemGenerator | `(item: any, index: number) => void`   | 是       | 组件生成函数。<br/>- 为数组中的每个元素创建对应的组件。<br/>- `item`参数:`arr`数组中的数据项。<br/>- `index`参数(可选):`arr`数组中的数据项索引。<br/>**说明:**<br/>- 组件的类型必须是`ForEach`的父容器所允许的。例如,`ListItem`组件要求`ForEach`的父容器组件必须为`List`组件。 |
27| keyGenerator  | `(item: any, index: number) => string` | 否       | 键值生成函数。<br/>- 为数据源`arr`的每个数组项生成唯一且持久的键值。函数返回值为开发者自定义的键值生成规则。<br/>- `item`参数:`arr`数组中的数据项。<br/>- `index`参数(可选):`arr`数组中的数据项索引。<br/>**说明:**<br/>- 如果函数缺省,框架默认的键值生成函数为`(item: T, index: number) => { return index + '__' + JSON.stringify(item); }`<br/>- 键值生成函数不应改变任何组件状态。 |
28
29> **说明:**
30>
31> - `ForEach`的`itemGenerator`函数可以包含`if/else`条件渲染逻辑。另外,也可以在`if/else`条件渲染语句中使用`ForEach`组件。
32> - 在初始化渲染时,`ForEach`会加载数据源的所有数据,并为每个数据项创建对应的组件,然后将其挂载到渲染树上。如果数据源非常大或有特定的性能需求,建议使用`LazyForEach`组件。
33
34## 键值生成规则
35
36在`ForEach`循环渲染过程中,系统会为每个数组元素生成一个唯一且持久的键值,用于标识对应的组件。当这个键值变化时,ArkUI框架将视为该数组元素已被替换或修改,并会基于新的键值创建一个新的组件。
37
38`ForEach`提供了一个名为`keyGenerator`的参数,这是一个函数,开发者可以通过它自定义键值的生成规则。如果开发者没有定义`keyGenerator`函数,则ArkUI框架会使用默认的键值生成函数,即`(item: any, index: number) => { return index + '__' + JSON.stringify(item); }`。
39
40ArkUI框架对于`ForEach`的键值生成有一套特定的判断规则,这主要与`itemGenerator`函数的第二个参数`index`以及`keyGenerator`函数的第二个参数`index`有关,具体的键值生成规则判断逻辑如下图所示。
41
42**图1** ForEach键值生成规则
43![ForEach-Key-Generation-Rules](figures/ForEach-Key-Generation-Rules.png)
44
45> **说明:**
46>
47> ArkUI框架会对重复的键值发出警告。在UI更新的场景下,如果出现重复的键值,框架可能无法正常工作,具体请参见[渲染结果非预期](#渲染结果非预期)。
48
49## 组件创建规则
50
51在确定键值生成规则后,ForEach的第二个参数`itemGenerator`函数会根据键值生成规则为数据源的每个数组项创建组件。组件的创建包括两种情况:[ForEach首次渲染](#首次渲染)和[ForEach非首次渲染](#非首次渲染)。
52
53### 首次渲染
54
55在ForEach首次渲染时,会根据前述键值生成规则为数据源的每个数组项生成唯一键值,并创建相应的组件。
56
57```ts
58@Entry
59@Component
60struct Parent {
61  @State simpleList: Array<string> = ['one', 'two', 'three'];
62
63  build() {
64    Row() {
65      Column() {
66        ForEach(this.simpleList, (item: string) => {
67          ChildItem({ item: item })
68        }, (item: string) => item)
69      }
70      .width('100%')
71      .height('100%')
72    }
73    .height('100%')
74    .backgroundColor(0xF1F3F5)
75  }
76}
77
78@Component
79struct ChildItem {
80  @Prop item: string;
81
82  build() {
83    Text(this.item)
84      .fontSize(50)
85  }
86}
87```
88
89运行效果如下图所示。
90
91**图2**  ForEach数据源不存在相同值案例首次渲染运行效果图
92![ForEach-CaseStudy-1stRender-NoDup](figures/ForEach-CaseStudy-1stRender-NoDup.png)
93
94在上述代码中,键值生成规则是`keyGenerator`函数的返回值`item`。在ForEach渲染循环时,为数据源数组项依次生成键值`one`、`two`和`three`,并创建对应的`ChildItem`组件渲染到界面上。
95
96当不同数组项按照键值生成规则生成的键值相同时,框架的行为是未定义的。例如,在以下代码中,ForEach渲染相同的数据项`two`时,只创建了一个`ChildItem`组件,而没有创建多个具有相同键值的组件。
97
98 ```ts
99 @Entry
100 @Component
101 struct Parent {
102   @State simpleList: Array<string> = ['one', 'two', 'two', 'three'];
103
104   build() {
105     Row() {
106       Column() {
107         ForEach(this.simpleList, (item: string) => {
108           ChildItem({ item: item })
109         }, (item: string) => item)
110       }
111       .width('100%')
112       .height('100%')
113     }
114     .height('100%')
115     .backgroundColor(0xF1F3F5)
116   }
117 }
118
119 @Component
120 struct ChildItem {
121   @Prop item: string;
122
123   build() {
124     Text(this.item)
125       .fontSize(50)
126   }
127 }
128 ```
129
130运行效果如下图所示。
131
132**图3**  ForEach数据源存在相同值案例首次渲染运行效果图
133![ForEach-CaseStudy-1stRender-Dup](figures/ForEach-CaseStudy-1stRender-Dup.png)
134
135在该示例中,最终键值生成规则为`item`。当ForEach遍历数据源`simpleList`,遍历到索引为1的`two`时,按照最终键值生成规则生成键值为`two`的组件并进行标记。当遍历到索引为2的`two`时,按照最终键值生成规则当前项的键值也为`two`,此时不再创建新的组件。
136
137### 非首次渲染
138
139在ForEach组件进行非首次渲染时,它会检查新生成的键值是否在上次渲染中已经存在。如果键值不存在,则会创建一个新的组件;如果键值存在,则不会创建新的组件,而是直接渲染该键值所对应的组件。例如,在以下的代码示例中,通过点击事件修改了数组的第三项值为"new three",这将触发ForEach组件进行非首次渲染。
140
141```ts
142@Entry
143@Component
144struct Parent {
145  @State simpleList: Array<string> = ['one', 'two', 'three'];
146
147  build() {
148    Row() {
149      Column() {
150        Text('点击修改第3个数组项的值')
151          .fontSize(24)
152          .fontColor(Color.Red)
153          .onClick(() => {
154            this.simpleList[2] = 'new three';
155          })
156
157        ForEach(this.simpleList, (item: string) => {
158          ChildItem({ item: item })
159            .margin({ top: 20 })
160        }, (item: string) => item)
161      }
162      .justifyContent(FlexAlign.Center)
163      .width('100%')
164      .height('100%')
165    }
166    .height('100%')
167    .backgroundColor(0xF1F3F5)
168  }
169}
170
171@Component
172struct ChildItem {
173  @Prop item: string;
174
175  build() {
176    Text(this.item)
177      .fontSize(30)
178  }
179}
180```
181
182运行效果如下图所示。
183
184**图4**  ForEach非首次渲染案例运行效果图
185![ForEach-Non-Initial-Render-Case-Effect](figures/ForEach-Non-Initial-Render-Case-Effect.gif)
186
187从本例可以看出`@State` 能够监听到简单数据类型数组数据源 `simpleList` 数组项的变化。
188
1891. 当 `simpleList` 数组项发生变化时,会触发 `ForEach` 进行重新渲染。
1902. `ForEach` 遍历新的数据源 `['one', 'two', 'new three']`,并生成对应的键值`one`、`two`和`new three`。
1913. 其中,键值`one`和`two`在上次渲染中已经存在,所以 `ForEach` 复用了对应的组件并进行了渲染。对于第三个数组项 "new three",由于其通过键值生成规则 `item` 生成的键值`new three`在上次渲染中不存在,因此 `ForEach` 为该数组项创建了一个新的组件。
192
193## 使用场景
194
195ForEach组件在开发过程中的主要应用场景包括:[数据源不变](#数据源不变)、[数据源数组项发生变化](#数据源数组项发生变化)(如插入、删除操作)、[数据源数组项子属性变化](#数据源数组项子属性变化)。
196
197### 数据源不变
198
199在数据源保持不变的场景中,数据源可以直接采用基本数据类型。例如,在页面加载状态时,可以使用骨架屏列表进行渲染展示。
200
201```ts
202@Entry
203@Component
204struct ArticleList {
205  @State simpleList: Array<number> = [1, 2, 3, 4, 5];
206
207  build() {
208    Column() {
209      ForEach(this.simpleList, (item: number) => {
210        ArticleSkeletonView()
211          .margin({ top: 20 })
212      }, (item: number) => item.toString())
213    }
214    .padding(20)
215    .width('100%')
216    .height('100%')
217  }
218}
219
220@Builder
221function textArea(width: number | Resource | string = '100%', height: number | Resource | string = '100%') {
222  Row()
223    .width(width)
224    .height(height)
225    .backgroundColor('#FFF2F3F4')
226}
227
228@Component
229struct ArticleSkeletonView {
230  build() {
231    Row() {
232      Column() {
233        textArea(80, 80)
234      }
235      .margin({ right: 20 })
236
237      Column() {
238        textArea('60%', 20)
239        textArea('50%', 20)
240      }
241      .alignItems(HorizontalAlign.Start)
242      .justifyContent(FlexAlign.SpaceAround)
243      .height('100%')
244    }
245    .padding(20)
246    .borderRadius(12)
247    .backgroundColor('#FFECECEC')
248    .height(120)
249    .width('100%')
250    .justifyContent(FlexAlign.SpaceBetween)
251  }
252}
253```
254
255运行效果如下图所示。
256
257**图5** 骨架屏运行效果图
258![ForEach-SkeletonScreen](figures/ForEach-SkeletonScreen.png)
259
260在本示例中,采用数据项item作为键值生成规则,由于数据源simpleList的数组项各不相同,因此能够保证键值的唯一性。
261
262### 数据源数组项发生变化
263
264在数据源数组项发生变化的场景下,例如进行数组插入、删除操作或者数组项索引位置发生交换时,数据源应为对象数组类型,并使用对象的唯一ID作为最终键值。例如,当在页面上通过手势上滑加载下一页数据时,会在数据源数组尾部新增新获取的数据项,从而使得数据源数组长度增大。
265
266```ts
267class Article {
268  id: string;
269  title: string;
270  brief: string;
271
272  constructor(id: string, title: string, brief: string) {
273    this.id = id;
274    this.title = title;
275    this.brief = brief;
276  }
277}
278
279@Entry
280@Component
281struct ArticleListView {
282  @State isListReachEnd: boolean = false;
283  @State articleList: Array<Article> = [
284    new Article('001', '第1篇文章', '文章简介内容'),
285    new Article('002', '第2篇文章', '文章简介内容'),
286    new Article('003', '第3篇文章', '文章简介内容'),
287    new Article('004', '第4篇文章', '文章简介内容'),
288    new Article('005', '第5篇文章', '文章简介内容'),
289    new Article('006', '第6篇文章', '文章简介内容')
290  ]
291
292  loadMoreArticles() {
293    this.articleList.push(new Article('007', '加载的新文章', '文章简介内容'));
294  }
295
296  build() {
297    Column({ space: 5 }) {
298      List() {
299        ForEach(this.articleList, (item: Article) => {
300          ListItem() {
301            ArticleCard({ article: item })
302              .margin({ top: 20 })
303          }
304        }, (item: Article) => item.id)
305      }
306      .onReachEnd(() => {
307        this.isListReachEnd = true;
308      })
309      .parallelGesture(
310        PanGesture({ direction: PanDirection.Up, distance: 80 })
311          .onActionStart(() => {
312            if (this.isListReachEnd) {
313              this.loadMoreArticles();
314              this.isListReachEnd = false;
315            }
316          })
317      )
318      .padding(20)
319      .scrollBar(BarState.Off)
320    }
321    .width('100%')
322    .height('100%')
323    .backgroundColor(0xF1F3F5)
324  }
325}
326
327@Component
328struct ArticleCard {
329  @Prop article: Article;
330
331  build() {
332    Row() {
333      Image($r('app.media.icon'))
334        .width(80)
335        .height(80)
336        .margin({ right: 20 })
337
338      Column() {
339        Text(this.article.title)
340          .fontSize(20)
341          .margin({ bottom: 8 })
342        Text(this.article.brief)
343          .fontSize(16)
344          .fontColor(Color.Gray)
345          .margin({ bottom: 8 })
346      }
347      .alignItems(HorizontalAlign.Start)
348      .width('80%')
349      .height('100%')
350    }
351    .padding(20)
352    .borderRadius(12)
353    .backgroundColor('#FFECECEC')
354    .height(120)
355    .width('100%')
356    .justifyContent(FlexAlign.SpaceBetween)
357  }
358}
359```
360
361初始运行效果(左图)和手势上滑加载后效果(右图)如下图所示。
362
363**图6**  数据源数组项变化案例运行效果图
364![ForEach-DataSourceArrayChange](figures/ForEach-DataSourceArrayChange.png)
365
366在本示例中,`ArticleCard`组件作为`ArticleListView`组件的子组件,通过`@Prop`装饰器接收一个`Article`对象,用于渲染文章卡片。
367
3681. 当列表滚动到底部时,如果手势滑动距离超过指定的80,将触发`loadMoreArticle()`函数。此函数会在`articleList`数据源的尾部添加一个新的数据项,从而增加数据源的长度。
3692. 数据源被`@State`装饰器修饰,ArkUI框架能够感知到数据源长度的变化,并触发`ForEach`进行重新渲染。
370
371### 数据源数组项子属性变化
372
373当数据源的数组项为对象数据类型,并且只修改某个数组项的属性值时,由于数据源为复杂数据类型,ArkUI框架无法监听到`@State`装饰器修饰的数据源数组项的属性变化,从而无法触发`ForEach`的重新渲染。为实现`ForEach`重新渲染,需要结合`@Observed`和`@ObjectLink`装饰器使用。例如,在文章列表卡片上点击“点赞”按钮,从而修改文章的点赞数量。
374
375```ts
376@Observed
377class Article {
378  id: string;
379  title: string;
380  brief: string;
381  isLiked: boolean;
382  likesCount: number;
383
384  constructor(id: string, title: string, brief: string, isLiked: boolean, likesCount: number) {
385    this.id = id;
386    this.title = title;
387    this.brief = brief;
388    this.isLiked = isLiked;
389    this.likesCount = likesCount;
390  }
391}
392
393@Entry
394@Component
395struct ArticleListView {
396  @State articleList: Array<Article> = [
397    new Article('001', '第0篇文章', '文章简介内容', false, 100),
398    new Article('002', '第1篇文章', '文章简介内容', false, 100),
399    new Article('003', '第2篇文章', '文章简介内容', false, 100),
400    new Article('004', '第4篇文章', '文章简介内容', false, 100),
401    new Article('005', '第5篇文章', '文章简介内容', false, 100),
402    new Article('006', '第6篇文章', '文章简介内容', false, 100),
403  ];
404
405  build() {
406    List() {
407      ForEach(this.articleList, (item: Article) => {
408        ListItem() {
409          ArticleCard({
410            article: item
411          })
412            .margin({ top: 20 })
413        }
414      }, (item: Article) => item.id)
415    }
416    .padding(20)
417    .scrollBar(BarState.Off)
418    .backgroundColor(0xF1F3F5)
419  }
420}
421
422@Component
423struct ArticleCard {
424  @ObjectLink article: Article;
425
426  handleLiked() {
427    this.article.isLiked = !this.article.isLiked;
428    this.article.likesCount = this.article.isLiked ? this.article.likesCount + 1 : this.article.likesCount - 1;
429  }
430
431  build() {
432    Row() {
433      Image($r('app.media.icon'))
434        .width(80)
435        .height(80)
436        .margin({ right: 20 })
437
438      Column() {
439        Text(this.article.title)
440          .fontSize(20)
441          .margin({ bottom: 8 })
442        Text(this.article.brief)
443          .fontSize(16)
444          .fontColor(Color.Gray)
445          .margin({ bottom: 8 })
446
447        Row() {
448          Image(this.article.isLiked ? $r('app.media.iconLiked') : $r('app.media.iconUnLiked'))
449            .width(24)
450            .height(24)
451            .margin({ right: 8 })
452          Text(this.article.likesCount.toString())
453            .fontSize(16)
454        }
455        .onClick(() => this.handleLiked())
456        .justifyContent(FlexAlign.Center)
457      }
458      .alignItems(HorizontalAlign.Start)
459      .width('80%')
460      .height('100%')
461    }
462    .padding(20)
463    .borderRadius(12)
464    .backgroundColor('#FFECECEC')
465    .height(120)
466    .width('100%')
467    .justifyContent(FlexAlign.SpaceBetween)
468  }
469}
470```
471
472上述代码的初始运行效果(左图)和点击第1个文章卡片上的点赞图标后的运行效果(右图)如下图所示。
473
474**图7** 数据源数组项子属性变化案例运行效果图
475![ForEach-DataSourceArraySubpropertyChange](figures/ForEach-DataSourceArraySubpropertyChange.png)
476
477在本示例中,`Article`类被`@Observed`装饰器修饰。父组件`ArticleListView`传入`Article`对象实例给子组件`ArticleCard`,子组件使用`@ObjectLink`装饰器接收该实例。
478
4791. 当点击第1个文章卡片上的点赞图标时,会触发`ArticleCard`组件的`handleLiked`函数。该函数修改第1个卡片对应组件里`article`实例的`isLiked`和`likesCount`属性值。
4802. 由于子组件`ArticleCard`中的`article`使用了`@ObjectLink`装饰器,父子组件共享同一份`article`数据。因此,父组件中`articleList`的第1个数组项的`isLiked`和`likedCounts`数值也会同步修改。
4813. 当父组件监听到数据源数组项属性值变化时,会触发`ForEach`重新渲染。
4824. 在此处,`ForEach`键值生成规则为数组项的`id`属性值。当`ForEach`遍历新数据源时,数组项的`id`均没有变化,不会新建组件。
4835. 渲染第1个数组项对应的`ArticleCard`组件时,读取到的`isLiked`和`likesCount`为修改后的新值。
484
485## 使用建议
486
487- 尽量避免在最终的键值生成规则中包含数据项索引`index`,以防止出现[渲染结果非预期](#渲染结果非预期)和[渲染性能降低](#渲染性能降低)。如果业务确实需要使用`index`,例如列表需要通过`index`进行条件渲染,开发者需要接受`ForEach`在改变数据源后重新创建组件所带来的性能损耗。
488- 为满足键值的唯一性,对于对象数据类型,建议使用对象数据中的唯一`id`作为键值。
489- 基本数据类型的数据项没有唯一`ID`属性。如果使用基本数据类型本身作为键值,必须确保数组项无重复。因此,对于数据源会发生变化的场景,建议将基本数据类型数组转化为具备唯一`ID`属性的对象数据类型数组,再使用`ID`属性作为键值生成规则。
490
491## 不推荐案例
492
493开发者在使用ForEach的过程中,若对于键值生成规则的理解不够充分,可能会出现错误的使用方式。错误使用一方面会导致功能层面问题,例如[渲染结果非预期](#渲染结果非预期),另一方面会导致性能层面问题,例如[渲染性能降低](#渲染性能降低)。
494
495### 渲染结果非预期
496
497在本示例中,通过设置`ForEach`的第三个参数`KeyGenerator`函数,自定义键值生成规则为数据源的索引`index`的字符串类型值。当点击父组件`Parent`中“在第1项后插入新项”文本组件后,界面会出现非预期的结果。
498
499```ts
500@Entry
501@Component
502struct Parent {
503  @State simpleList: Array<string> = ['one', 'two', 'three'];
504
505  build() {
506    Column() {
507      Button() {
508        Text('在第1项后插入新项').fontSize(30)
509      }
510      .onClick(() => {
511        this.simpleList.splice(1, 0, 'new item');
512      })
513
514      ForEach(this.simpleList, (item: string) => {
515        ChildItem({ item: item })
516      }, (item: string, index: number) => index.toString())
517    }
518    .justifyContent(FlexAlign.Center)
519    .width('100%')
520    .height('100%')
521    .backgroundColor(0xF1F3F5)
522  }
523}
524
525@Component
526struct ChildItem {
527  @Prop item: string;
528
529  build() {
530    Text(this.item)
531      .fontSize(30)
532  }
533}
534```
535
536上述代码的初始渲染效果和点击“在第1项后插入新项”文本组件后的渲染效果如下图所示。
537
538**图8**  渲染结果非预期运行效果图
539![ForEach-UnexpectedRenderingResult](figures/ForEach-UnexpectedRenderingResult.gif)
540
541`ForEach`在首次渲染时,创建的键值依次为"0"、"1"、"2"。
542
543插入新项后,数据源`simpleList`变为`['one', 'new item', 'two', 'three']`,框架监听到`@State`装饰的数据源长度变化触发`ForEach`重新渲染。
544
545`ForEach`依次遍历新数据源,遍历数据项"one"时生成键值"0",存在相同键值,因此不创建新组件。继续遍历数据项"new item"时生成键值"1",存在相同键值,因此不创建新组件。继续遍历数据项"two"生成键值"2",存在相同键值,因此不创建新组件。最后遍历数据项"three"时生成键值"3",不存在相同键值,创建内容为"three"的新组件并渲染。
546
547从以上可以看出,当最终键值生成规则包含`index`时,期望的界面渲染结果为`['one', 'new item', 'two', 'three']`,而实际的渲染结果为`['one', 'two', 'three', 'three']`,渲染结果不符合开发者预期。因此,开发者在使用`ForEach`时应尽量避免最终键值生成规则中包含`index`。
548
549### 渲染性能降低
550
551在本示例中,`ForEach`的第三个参数`KeyGenerator`函数处于缺省状态。根据上述[键值生成规则](#键值生成规则),此例使用框架默认的键值生成规则,即最终键值为字符串`index + '__' + JSON.stringify(item)`。当点击“在第1项后插入新项”文本组件后,`ForEach`将需要为第2个数组项以及其后的所有项重新创建组件。
552
553```ts
554@Entry
555@Component
556struct Parent {
557  @State simpleList: Array<string> = ['one', 'two', 'three'];
558
559  build() {
560    Column() {
561      Button() {
562        Text('在第1项后插入新项').fontSize(30)
563      }
564      .onClick(() => {
565        this.simpleList.splice(1, 0, 'new item');
566        console.log(`[onClick]: simpleList is ${JSON.stringify(this.simpleList)}`);
567      })
568
569      ForEach(this.simpleList, (item: string) => {
570        ChildItem({ item: item })
571      })
572    }
573    .justifyContent(FlexAlign.Center)
574    .width('100%')
575    .height('100%')
576    .backgroundColor(0xF1F3F5)
577  }
578}
579
580@Component
581struct ChildItem {
582  @Prop item: string;
583
584  aboutToAppear() {
585    console.log(`[aboutToAppear]: item is ${this.item}`);
586  }
587
588  build() {
589    Text(this.item)
590      .fontSize(50)
591  }
592}
593```
594
595以上代码的初始渲染效果和点击"在第1项后插入新项"文本组件后的渲染效果如下图所示。
596
597**图9**  渲染性能降低案例运行效果图
598![ForEach-RenderPerformanceDecrease](figures/ForEach-RenderPerformanceDecrease.gif)
599
600点击“在第1项后插入新项”文本组件后,IDE的日志打印结果如下所示。
601
602**图10**  渲染性能降低案例日志打印图
603![ForEach-RenderPerformanceDecreaseLogs](figures/ForEach-RenderPerformanceDecreaseLogs.png)
604
605插入新项后,`ForEach`为`new item`、 `two`、 `three`三个数组项创建了对应的组件`ChildItem`,并执行了组件的[`aboutToAppear()`](../reference/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear)生命周期函数。这是因为:
606
6071. 在`ForEach`首次渲染时,创建的键值依次为`0__one`、`1__two`、`2__three`。
6082. 插入新项后,数据源`simpleList`变为`['one', 'new item', 'two', 'three']`,ArkUI框架监听到`@State`装饰的数据源长度变化触发`ForEach`重新渲染。
6093. `ForEach`依次遍历新数据源,遍历数据项`one`时生成键值`0__one`,键值已存在,因此不创建新组件。继续遍历数据项`new item`时生成键值`1__new item`,不存在相同键值,创建内容为`new item`的新组件并渲染。继续遍历数据项`two`生成键值`2__two`,不存在相同键值,创建内容为`two`的新组件并渲染。最后遍历数据项`three`时生成键值`3__three`,不存在相同键值,创建内容为`three`的新组件并渲染。
610
611尽管此示例中界面渲染的结果符合预期,但每次插入一条新数组项时,`ForEach`都会为从该数组项起后面的所有数组项全部重新创建组件。当数据源数据量较大或组件结构复杂时,由于组件无法得到复用,将导致性能体验不佳。因此,除非必要,否则不推荐将第三个参数`KeyGenerator`函数处于缺省状态,以及在键值生成规则中包含数据项索引`index`。
612