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修饰对象数组,直接修改对象的属性时,系统无法监听到数组中的对象的属性变化,造成页面无法渲染刷新。
- 在状态管理V1中要想观察到class中对象类型的某个属性的变化,需要@Observed/@ObjectLink配套使用
- 在状态管理V2中要想观察到class中对象类型的某个属性的变化,需要使用@ObservedV2装饰器与@Trace装饰器
更多关于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
的响应机制依赖于对象引用的变更,而单例实例的引用始终不变。
解决方案:
- 使用
@Observed
和@ObjectLink
:将单例类用@Observed
装饰,并在组件中使用@ObjectLink
引用实例。 - 通过赋值新实例触发更新(不适用于单例模式)。
- 在单例类中封装状态变更方法,并调用
this.voiceReadHelper = {...this.voiceReadHelper}
强制更新引用。
推荐重构代码,避免直接使用单例实例作为@State
变量,或采用状态管理方案如AppStorage。