鸿蒙开发笔记

鸿蒙开发笔记-9-应用状态管理:LocalStorage、App

2025-03-09  本文已影响0人  今阳说

一、基本概念

1. LocalStorage(页面级内存存储)

2. AppStorage(应用级全局状态池)

  1. 初始化策略:
    • AppStorage.SetOrCreate('theme', 'dark') 实现懒加载式初始化
    • 支持复杂对象存储(需配合@Observed装饰器)
  2. 访问方式:
    • @StorageProp:单向绑定(适合全局配置读取)
    • @StorageLink:双向绑定(如用户登录状态全局同步)

3. PersistentStorage(持久化存储引擎)

二、对比分析

维度 LocalStorage AppStorage PersistentStorage
存储位置 内存(页面级) 内存(应用级) 磁盘(持久化)
数据类型 简单类型+可序列化对象 复杂类型(需@Observed 简单类型+部分复杂类型
同步方式 单向/双向(内存操作) 双向(内存操作) 异步持久化(磁盘IO)
安全风险 内存泄露风险 数据泄露/篡改风险
典型延迟 μs级 μs级 ms级(磁盘写入)
适用场景 临时状态、页面间通信 全局状态共享 配置数据、历史记录

三、使用场景

1. LocalStorage
typescript
// 页面级主题管理
const storage = new LocalStorage({ 'theme': 'light' });

@Entry(storage)
@Component struct ThemePage {
  @LocalStorageLink('theme') currentTheme: string = 'light'
  
  build() {
    Column() {
      ThemeSwitcher({ theme: $$this.currentTheme })
      ContentArea()
    }.backgroundColor(this.currentTheme === 'dark' ? '#333' : '#FFF')
  }
}
2. AppStorage
typescript
// 全局登录状态管理
AppStorage.setOrCreate('isLoggedIn', false)

@Entry
@Component struct MainEntry {
  @StorageLink('isLoggedIn') isLogin: boolean = false

  build() {
    Column() {
      if (this.isLogin) {
        HomePage()
      } else {
        LoginPage()
      }
    }
  }
}

关键特性

3. PersistentStorage
typescript
// 持久化用户设置
PersistentStorage.persistProp('userSettings', {
  fontSize: 14,
  notification: true
})

@Entry
@Component struct SettingsPage {
  @StorageLink('userSettings') settings: any = {}

  changeFontSize(size: number) {
    this.settings.fontSize = size
  }
}
4. PersistentStorage加密方案
// 静态数据加密(AES-256)
import { cryptoFramework } from '@ohos.security.crypto';

async function securePersist(key: string, value: string) {
  const cipher = await cryptoFramework.createCipher('AES128|ECB|PKCS7', 'your-secret-key');
  const encrypted = cipher.encrypt(value);
  PersistentStorage.persistProp(key, encrypted);
}

安全建议

5. PersistentStorage状态更新策略
typescript
// 推荐更新方式
class UpdateService {
  static updateGlobalState(key: string, value: any) {
    if (needPersist(key)) {
      PersistentStorage.persistProp(key, value)
    }
    AppStorage.setOrCreate(key, value)
  }
}
6. 状态恢复与容灾
// 应用启动时数据校验
windowStage.loadContent('pages/Index', async (err) => {
  if (err) {
    console.error('Failed to load content:', err);
    return;
  }
  const lastData = await PersistentStorage.get('criticalData');
  if (!lastData) {
    // 从云端备份恢复
    const backup = await fetchBackup();
    PersistentStorage.persistProp('criticalData', backup);
  }
});

容灾策略

四、总结

我是今阳,如果想要进阶和了解更多的干货,欢迎关注微信公众号 “今阳说” 接收我的最新文章

上一篇 下一篇

猜你喜欢

热点阅读