赞
踩
数组列表 / ForEach / 循环 / 实时更新
使用ForEach加载数组,是否必须要改变循环数组的唯一标识或者重新加载才可以更新。
使用ForEach加载数组,实现实时更新的注意点如下:
在代码中ForEach使用的数据对象已被状态变量修饰。
数据变化前后ForEach生成的子组件键值发生了变化,需要通过ID变化的方式进行更新并保证生成的ID唯一,可以使用JSON.stringify。
遍历的数组变化时,UI不一定会刷新的两个案例,具体如下。
案例一
例如:this.arr = [new Item(1, '1'), new Item(2, '2'), new Item(3, '3')] 时,
- ForEach(this.arr, (item: any) => {
- ListItem() {
- Text(item.id + item.val)
- }}, (item: any) => item.id.toString())
更改值this.arr[1] = new Item(2, '4'),修改数据内容时Item对象的id没有发生变化,导致item.id.toString()在数组变化前后没有改变,UI不会刷新。
但是,如果写成:this.arr[1] = new Item(4, '4'),UI会刷新。
案例二:
如下写法,点击事件触发时,UI也不会刷新。
- @Entry
- @Component
- struct IndexOne {
- @State arr: any[] = []
-
- aboutToAppear() {
- this.arr = [new Item(1, '1'), new Item(2, '2'), new Item(3, '3')];
- }
-
- build() {
- Column() {
- Button('change second value')
- .onClick(()=>{
- // 修改数据内容时Item对象的id没有发生变化,导致item.id.toString()在数组变化前后没有改变,界面不刷新。
- this.arr = this.arr.concat([new Item(2, '4'), new Item(3, '5')])
- })
- List() {
- ForEach(this.arr, (item: any) => {
- ListItem() {
- Text(item.id + item.val)
- }
- }, (item: any) => item.id.toString())
- }.width('100%').height(300)
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。