HarmonyOS PersistentStorage无效?

想通过PersistentStorage持久化一些数据。启动时初始化PersistentStorage,然后在页面中点击按钮更新数据。但是操作完成后,终止app启动时依然拿不到上次保存的数据。

操作顺序为:

// 应用启动
PersistentStorage.persistProp("isLogin", false)
PersistentStorage.persistProp("user", new UserModel())

//点击按钮
const model = new UserModel()
model.username = "xxx"
model.customerNo = "88888888"
model.branchName = "Main Branch"
model.branchNo = "999999"

AppStorage.setOrCreate("user", model)
AppStorage.setOrCreate("isLogin", true)
阅读 581
1 个回答

PersistentStorage和UIContext相关联,需要在UIContext明确的时候才可以调用,可以通过在runScopedTask里明确上下文。如果没有在UIContext明确的地方调用,将导致无法持久化数据。在onWindowStageCreate中调用示例如下:

onWindowStageCreate(windowStage: window.WindowStage): void {
  windowStage.loadContent('pages/Index', (err) => {
    if (err.code) {
      return;
    }
    let window = windowStage.getMainWindow();
    window.then(win => {
      let uiContext = win.getUIContext();
      uiContext.runScopedTask(() => {
        const keys = PersistentStorage.keys()
        hilog.info(0x0000, 'UUUUU', "keys -> " + keys[0] + " , " + keys[1]);

        PersistentStorage.persistProp("isLogin", false)
        PersistentStorage.persistProp("user", new UserModel())

        hilog.info(0x0000, 'UUUUU', "isLogin -> " + JSON.stringify(AppStorage.get("isLogin")));
        hilog.info(0x0000, 'UUUUU', "user -> " + JSON.stringify(AppStorage.get("user")));
      })
    })
  });
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进