HarmonyOS 状态变量不刷新问题?

下面这段代码在点击每个Item删除数组元素时,问什么没刷新到UI上。

//状态变量问题 
class Article { 
  id: string; 
  title: string; 
  brief: string; 
  constructor(id: string, title: string, brief: string) { 
    this.id = id; 
    this.title = title; 
    this.brief = brief; 
  } 
} 
class Arrtest{ 
  articleList: Array<Article> = [ 
    new Article('001', '第1篇文章', '文章简介内容'), 
    new Article('002', '第2篇文章', '文章简介内容'), 
    new Article('003', '第3篇文章', '文章简介内容'), 
    new Article('004', '第4篇文章', '文章简介内容'), 
    new Article('005', '第5篇文章', '文章简介内容'), 
    new Article('006', '第6篇文章', '文章简介内容') 
  ] 
} 
@Entry 
@Component 
struct ArticleListView { 
  @State isListReachEnd: boolean = false; 
  @State arrtest: Arrtest = new Arrtest() 
 
  build() { 
    Column({ space: 5 }) { 
      Flex() { 
        ForEach(this.arrtest.articleList, (item: Article, index: number) => { 
          ListItem() { 
            this.articleCard(index) 
          } 
        }, (item: Article) => item.id) 
      } 
      .padding(20) 
    } 
    .width('100%') 
    .height('100%') 
    .backgroundColor(0xF1F3F5) 
  } 
 
  @Builder 
  articleCard(index: number) { 
    Row() { 
      Column() { 
        Text('test') 
          .fontSize(20) 
          .margin({ bottom: 8 }) 
      } 
      .alignItems(HorizontalAlign.Start) 
      .width('80%') 
      .height('100%') 
    } 
    .padding(20) 
    .borderRadius(12) 
    .backgroundColor('#FFECECEC') 
    .height(120) 
    .width('100%') 
    .justifyContent(FlexAlign.SpaceBetween) 
    .onClick(() => { 
      this.arrtest.articleList?.splice(index, 1) 
    }) 
} 
}
阅读 522
1 个回答

解决方案

可参考如下关键代码:

.onClick(() => { 
  this.arrtest.articleList?.splice(index, 1); 
  this.arrtest.articleList = this.arrtest.articleList.concat([]); 
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进