偶然发现AppStorage静态方法在函数逻辑中可以修改AppStorage管理的全局变量,因此我尝试使用了这个方法

在DataUtils中,我新增了一个静态方法,实现如下:

public static testAppStorage() {
    let cities: SubscribedAbstractProperty<City[]> = AppStorage.Link('storedCities');
    let base = cities.get();
    Logger.info(TAG, "base got", base);
    if (base.length > 0) {
      base[0].name = "测试成功";
      cities.set(base);
    } else {
      Logger.info(TAG, "base length is 0");
    }
  }

其中,City是一个接口,其实现如下:

export interface City{
  name: string;
  id: string;
  lat: string,
  lon: string,
  adm2: string;
  adm1: string;
  country: string;
  tz: string;
  utcOffset: string;
  isDst: string;
  type: string;
  rank: string;
  fxLink: string;
  isCurrentLocation?: boolean;
}

接着,我在EditPage中的某个组件上绑定了onClick事件,并在事件中调用`testAppStorage`方法

EditWeatherCard({
                  city,
                  warnings: this.warnings[index],
                  dailyWeather: this.dailyWeather[index],
                  realTimeWeather: this.realTimeWeather[index]
                })
                  .onClick(() => {
                    DataUtils.testAppStorage()
                    // router.back({ url: 'pages/Index', params: { 'weatherIndex': index } })
                  })

运行无报错,前往EditPage中点按EditWeatherCard组件后,发现UI不会刷新,回到Index页面,再次前往EditPage后,发现AppStorage中管理的'storedCities'变量确实已经发生改变,UI中显示”测试成功“

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐