异步回调更新数据源,无法触发列表渲染?

问题代码

// 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%') 
  } 
}
阅读 382
1 个回答

解决措施

ArkUI无法监听对象中数组属性的push变化,可以通过设置该数组对象触发UI界面刷新。

示例代码

// xxx.ets 
@Observed 
export class ChatListModel { 
  public chatItems: ObservedArray<ChatItemModel> = new ObservedArray<ChatItemModel>(); 
 
  fetChatList() { 
    setTimeout(() => { 
      let arr: ObservedArray<ChatItemModel> = new ObservedArray<ChatItemModel>(); 
      for (let i = 0; i < 30; i++) { 
        arr.push(new ChatItemModel(i.toString(), `小李${i}今天晚上放学不要走`)); 
      } 
      this.chatItems = arr; 
    }, 2000); 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进