下面这段代码在点击每个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)
})
}
}
解决方案
可参考如下关键代码: