HarmonyOS Observe的变量更新了,但是不会触发UI更新

Observe的变量更新了,但是不会触发UI更新。如下代码:通过 add,remove 按钮触发的数据变化,List 组件可以刷新,但是通过点击 ListItem 中的 Text.onClick 触发的数据变化,List 组件UI没有刷新。

@Entry 
@Component 
struct StatusPage { 
  @State config: TestConfig = new TestConfig() 
  build() { 
    Column({ space: 10 }) { 
      Text(this.config.sub.status) 
        .width('100%').backgroundColor(Color.Red) 
        .textAlign(TextAlign.Center) 
      Text(this.config.status) 
        .width('100%').backgroundColor(Color.Green) 
        .textAlign(TextAlign.Center) 
      List({ space: 5 }) { 
        ForEach(this.config.subList, (sub: SubConfig, index: number) => { 
          ListItem() { 
            Text(sub.status + ' 可点击删除') 
              .width('100%').height(50).backgroundColor(Color.Blue) 
              .textAlign(TextAlign.Center) 
              .onClick(() => { 
                this.config.removeIndex(index) 
              }) 
          } 
        }) 
      } 
      Button('add') 
        .onClick(() => { 
          this.config.add() 
        }) 
      Button('remove') 
        .onClick(() => { 
          this.config.remove() 
        }) 
    } 
    .width('100%').height('100%') 
    .justifyContent(FlexAlign.Center) 
  } 
} 
@Observed 
class TestConfig { 
  sub: SubConfig = new SubConfig('0') 
  status: string = '0' 
  subList: SubConfig[] = [] 
  add() { 
    this.status = (Number(this.status) + 1).toString() 
    this.sub.add() 
    this.subList.push(new SubConfig(this.status)) 
  } 
  remove() { 
    this.status = (Number(this.status) - 1).toString() 
    this.sub.remove() 
    this.subList.splice(0, 1) 
  } 
  removeIndex(index: number) { 
    this.subList.splice(index, 1) 
  } 
} 
@Observed 
class SubConfig { 
  status: string = '0' 
  constructor(status: string) { 
    this.status = status 
  } 
  add() { 
    this.status = (Number(this.status) + 1).toString() 
  } 
  remove() { 
    this.status = (Number(this.status) - 1).toString() 
  } 
}

“this.config.removeIndex(index)”为什么不生效。

HarmonyOS
2024-08-10 11:21:58
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

1this.config.removeIndex(index)修改的是this.config.subList的属性值,对于this.config.subList并没有用状态装饰器修饰,所以变化无法引起UI刷新。TestConfig的add和remove方法之所以能生效,是因为里面修改了status属性。而在StatusPage中TestConfig又用@State修饰了,这会导致status属性变化了之后能监听到变化,触发了UI刷新这个不是BUG,@Observed的用法可参考文档,文档中已表明:单独使用@Observed是没有任何作用的,需要搭配@ObjectLink或者@Prop使用。

分享
微博
QQ
微信
回复
2024-08-10 17:57:53
相关问题
callback无法成功更新UI
1712浏览 • 1回复 待解决
匿名内部类如何更新外部类变量
1484浏览 • 0回复 待解决
HarmonyOS应用更新demo
55浏览 • 1回复 待解决
HarmonyOS应用升级更新
92浏览 • 1回复 待解决
30s怎么更新什么时候更新
6626浏览 • 1回复 待解决
HarmonyOS Grid容器视图更新问题
152浏览 • 1回复 待解决
关于发布证书更新问题
59浏览 • 1回复 待解决