【关键字】
List / 嵌套数组 / Header / @State / 自定义类型 / 自定义类型数组 / 无法刷新
【问题描述】
使用List显示一个年级所有班级里的所有学生。ListItemGroup Header显示班级名称,能够悬停;ListItem显示当前班级的所有学生名称。数据更新时,列表无法监听到,导致无法刷新。
代码如下:
// 班级Model
import hilog from '@ohos.hilog'
class LCClassModel {
cId: string
cName: string
students: LCStudentArray = []
constructor(cId: string, cName: string, students: LCStudentArray = []) {
this.cId = cId
this.cName = cName
this.students = students
}
}
// 学生Model
@Observed
class LCStudentModel {
id: string
name: string
constructor(id: string, name: string) {
this.id = id
this.name = name
}
}
@Observed
class LCStudentArray extends Array<LCStudentModel> {}
@Entry
@Component
struct Index {
@State classes: LCClassModel[] = null
// 自定义 List Header
@Builder
classHeader(classModel: LCClassModel, index: number) {
Row() {
Text(classModel.cName)
.fontWeight(FontWeight.Medium)
.fontSize(20)
}
.width('100%')
.height('40')
.backgroundColor(Color.Red)
.onClick(() => {
let count = classModel.students.length
classModel.students.push( new LCStudentModel(`id_class${index}_${count}`, `name_class${index}_${count})`))
hilog.debug( 1, 'lc_saobei', JSON.stringify(this.classes))
})
}
aboutToAppear() {
this.classes = [
new LCClassModel('cID_0', '**鸿蒙先行班', [
new LCStudentModel('id_class0_0', 'name_class0_0')
])
]
}
build() {
Column() {
List() {
ForEach(this.classes, (classModel: LCClassModel, index) => {
ListItemGroup({ header: this.classHeader(classModel, index) }) {
ForEach(classModel.students, (studentModel: LCStudentModel) => {
ListItem() {
Row() {
Text(studentModel.name)
.fontSize(16)
}
.width('100%')
.height('30')
}
})
}
})
}
.sticky(StickyStyle.Header) // Header 悬停
}
}
}
【解决方案】
@State装饰器当前支持的变量类型为Object、class、string、number、boolean、enum类型以及这些类型的数组,Date类型,API11及以上支持Map、Set类型。不支持自定义类型和自定义类型数组。
因此,当自定义类型里的属性值发生变化时,无法触发页面刷新。