HarmonyOS鸿蒙Next中@State修饰一个单例模式类的实例时,变更该实例中的属性,UI没有刷新

HarmonyOS鸿蒙Next中@State修饰一个单例模式类的实例时,变更该实例中的属性,UI没有刷新

@Entry
@Component
struct Index {
  [@State](/user/State) private voiceReadHelper: VoiceReadHelper = VoiceReadHelper.getInstance()

  build() {
    Column() {
      Text()
        .backgroundColor(this.voiceReadHelper.isSpeaking ? Color.Yellow : Color.Red)
        .onClick(() => {
          this.voiceReadHelper.isSpeaking = !this.voiceReadHelper.isSpeaking
          // ...
        })
      // ...
    };
  }
}
export class VoiceReadHelper {
  private static instance: VoiceReadHelper | null = null
  isSpeaking = false
  private constructor() {
  }

  static getInstance(): VoiceReadHelper {
    if (VoiceReadHelper.instance == null) {
      VoiceReadHelper.instance = new VoiceReadHelper()
    }
    return VoiceReadHelper.instance
  }
}

更多关于HarmonyOS鸿蒙Next中@State修饰一个单例模式类的实例时,变更该实例中的属性,UI没有刷新的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

使用@State修饰对象数组,直接修改对象的属性时,系统无法监听到数组中的对象的属性变化,造成页面无法渲染刷新。

更多关于HarmonyOS鸿蒙Next中@State修饰一个单例模式类的实例时,变更该实例中的属性,UI没有刷新的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,@State装饰器仅能监听基本数据类型或简单类的属性变更。若修饰单例实例,其内部属性变化不会触发UI刷新,因为@State无法深度观察对象内部状态变化。单例对象本身引用未改变,导致ArkUI框架未检测到状态更新。需改用@Observed@ObjectLink装饰器,或通过自定义状态管理实现属性监听。

在HarmonyOS Next中,使用@State修饰单例实例时,直接修改其属性不会触发UI刷新。这是因为@State的响应机制依赖于对象引用的变更,而单例实例的引用始终不变。

解决方案:

  1. 使用@Observed@ObjectLink:将单例类用@Observed装饰,并在组件中使用@ObjectLink引用实例。
  2. 通过赋值新实例触发更新(不适用于单例模式)。
  3. 在单例类中封装状态变更方法,并调用this.voiceReadHelper = {...this.voiceReadHelper}强制更新引用。

推荐重构代码,避免直接使用单例实例作为@State变量,或采用状态管理方案如AppStorage。

回到顶部