在HarmonyOS NEXT开发中PersistentStorage 持久化的数据重启应用后数据为空?

在HarmonyOS NEXT开发中PersistentStorage 持久化的数据重启应用后数据为空?调用 PersistentStorage.persistProp 持久化失败
1.在按钮 onClick 事件中执行 PersistentStorage.persistProp(‘aProp’, 47)
2.重启应用后在按钮 onClick 事件中执行 AppStorage.get<number>(‘aProp’); // 返回 undefined

阅读 572
1 个回答

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

windowStage.loadContent(‘pages/Index’, (err, data) => { 
  if (err.code) { 
    hilog.error(0x0000, ‘testTag’, ‘Failed to load the content. Cause: %{public}s’, JSON.stringify(err) ?? ‘’); 
    return; 
  } 
  let window = windowStage.getMainWindow(); 
  window.then(win => { 
    let uiContext = win.getUIContext(); 
    uiContext.runScopedTask(() => { 
      PersistentStorage.persistProp(‘aProp’, 47); 
      // AppStorage.setOrCreate(“aProp”, 50) 
      console.log(11 $${AppStorage.get('aProp')}) 
    }) 
  }) 
  hilog.info(0x0000, ‘testTag’, ‘Succeeded in loading the content. Data: %{public}s’, JSON.stringify(data) ?? ‘’); 
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进