目录

@State修饰单例模式实例时无法刷新UI

问题现象

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

效果演示如下:在Page2中改变颜色后,返回Index页面,颜色没有同步刷新。

问题代码如下:

// Index.ets
import { VoiceReadHelper } from './VoiceReadHelper';

@Entry
@Component
struct Index {
  @State private voiceReadHelper: VoiceReadHelper = VoiceReadHelper.getInstance();

  build() {
    Column() {
      Text()
        .width(100)
        .height(100)
        .backgroundColor(this.voiceReadHelper.isSpeaking ? '#61CFBE' : '#8981F7')
        .borderRadius(8)
        .margin({ bottom: 100 })
        .onClick(() => {
          this.voiceReadHelper.isSpeaking = !this.voiceReadHelper.isSpeaking;
        });

      Text('去Page2').onClick(() => {
        this.getUIContext().getRouter().pushUrl({ url: 'pages/Page2' });
      });
    }
    .height('100%')
    .width('100%');
  }
}
// Page2.ets
import { VoiceReadHelper } from './VoiceReadHelper';

@Entry
@Component
struct Page2 {
  @State private voiceReadHelper: VoiceReadHelper = VoiceReadHelper.getInstance();

  build() {
    Column() {
      Text()
        .width(100)
        .height(100)
        .backgroundColor(this.voiceReadHelper.isSpeaking ? '#61CFBE' : '#8981F7')
        .borderRadius(8)
        .margin({ bottom: 100 })
        .onClick(() => {
          this.voiceReadHelper.isSpeaking = !this.voiceReadHelper.isSpeaking;
        });

      Text('这是Page2');
    }
    .height('100%')
    .width('100%');
  }
}
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;
  }
}

效果预览

背景知识

解决方案

总结

方案

适用场景

@State+@Observed

本地组件状态+单例对象引用,在需要使用的页面过多时难以维护,更适用于局部状态管理。

AppStorage

AppStorage就像一个“全局状态仓库”,所有组件通过@StorageLink('key')从仓库中读取状态,修改时也写回仓库,更适用于全局状态管理。同时,AppStorage中的属性可以通过PersistentStorage持久化写入硬盘,实现状态在重启后保留。