📌 背景说明

在中小型项目中,无需引入复杂的状态管理框架,也能使用 @State 和自定义类封装出一个简易版 Store,集中管理应用状态。


🧩 Step 1:定义 Store 状态类

// common/store.ts
import { reactive } from '@ohos.arkui';

class AppState {
  count: number = 0;
  username: string = '访客';

  increase() {
    this.count++;
  }

  setUsername(name: string) {
    this.username = name;
  }
}

// 使用 reactive 包裹,确保响应式
const store = reactive(new AppState());

export default store;

🧩 Step 2:在页面中使用 Store 状态

// pages/home/home.ets
import store from '../../common/store';

@Entry
@Component
struct HomePage {
  build() {
    Column() {
      Text(`欢迎:${store.username}`).fontSize(18).margin(10)
      Text(`计数器:${store.count}`).fontSize(18).margin(10)

      Button("增加").onClick(() => {
        store.increase();
      })

      Button("设置用户名").onClick(() => {
        store.setUsername("鸿蒙开发者");
      })
    }
    .padding(20)
  }
}

✅ 运行效果预览

  1. 点击 “增加” 按钮,计数器数字实时更新;

  2. 点击 “设置用户名”,文本会变为 “欢迎:鸿蒙开发者”。


⚠️ 易错点提醒

问题 说明
未使用 reactive() 状态不会自动更新 UI
直接 export class AppState 使用 会导致组件不响应数据变化
页面组件未消费状态值 则不会触发 UI 重新构建(无依赖追踪)

🧠 拓展建议

  • 多模块状态可封装多个 store 文件;

  • 可结合 EventHub 做异步通知;

  • 支持持久化:结合本地存储如 @ohos.data.storage 保存状态。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐