问题代码
// xxx.ets
@Observed
export class ObservedArray<T> extends Array<T> {
constructor(args?: T[]) {
if (args instanceof Array) {
super(...args);
} else {
super();
}
}
}
@Observed
export class ChatItemModel {
id_: string;
content: string;
constructor(msgId: string, content: string) {
this.id_ = msgId;
this.content = content;
}
}
@Observed
export class ChatListModel {
public chatItems: ObservedArray<ChatItemModel> = new ObservedArray<ChatItemModel>();
fetChatList() {
setTimeout(() => {
for (let i = 0; i < 30; i++) {
this.chatItems.push(new ChatItemModel(i.toString(), `小李${i}今天晚上放学不要走`));
}
}, 2000);
}
}
@Entry
@Component
export struct ChatList {
@State chatListModel: ChatListModel = new ChatListModel();
aboutToAppear() {
this.chatListModel.fetChatList();
}
build() {
List() {
ForEach(
this.chatListModel.chatItems,
(chatItem: ChatItemModel) => {
ListItem() {
Text(chatItem.content)
.margin({ left: 20, right: 20 })
}
.height(60)
.width('100%')
},
(chatItem: ChatItemModel): string => {
return chatItem.id_;
})
}
.height('100%')
.width('100%')
}
}
解决措施
ArkUI无法监听对象中数组属性的push变化,可以通过设置该数组对象触发UI界面刷新。
示例代码