HarmonyOS Next 状态管理:Type 装饰器实践

目录

  • HarmonyOS Next 状态管理:Local 装饰器实践
  • HarmonyOS Next 状态管理:Param 装饰器实践
  • HarmonyOS Next 状态管理:Once 装饰器实践
  • HarmonyOS Next 状态管理:Event 装饰器实践
  • HarmonyOS Next 状态管理:!! 状态装饰器实践
  • HarmonyOS Next 状态管理:@ObserverV2和@Trace 装饰器实践
  • HarmonyOS Next 状态管理:Provider和Consumer 装饰器实践
  • HarmonyOS Next 状态管理:Monitor 装饰器实践
  • HarmonyOS Next 状态管理:Computed 装饰器实践
  • # HarmonyOS Next 状态管理:Type 装饰器实践

一. @Type 修饰器概述

@Type 主要用于标记类属性的类型,以确保在序列化和反序列化过程中不会丢失属性的类型信息。它通常与 @ObservedV2 和 PersistenceV2 结合使用,用于实现复杂对象的持久化。

二. @Type的基本用法

2.1 基本语法
@Type(type: Class | BuiltInType)
  • type:指定属性的类型,可以是自定义类或内置类型(如 ArrayDateMapSet 等)。
2.2 使用示例
@ObservedV2
class SampleChild {
  @Trace p1: number = 0;
  p2: number = 10;
}

@ObservedV2
class Sample {
  @Type(SampleChild) // 标记属性 f 的类型为 SampleChild
  @Trace f: SampleChild = new SampleChild();
}
  • 在上面的代码中,@Type(SampleChild) 标记了属性 f 的类型为 SampleChild,确保在序列化和反序列化过程中不会丢失 SampleChild 的类型信息。

三. @Type的限制

3.1 只能用于 @ObservedV2 装饰的类

@Type 只能用于被 @ObservedV2 装饰的类中,不能用于普通类或自定义组件中。

@ObservedV2
class Info {
  @Type(Sample)
  @Trace sample: Sample = new Sample(); // 正确用法
}

@Observed
class Info2 {
  @Type(Sample)
  sample: Sample = new Sample(); // 错误用法,不能用在 @Observed 装饰的类中
}

@ComponentV2
struct Index {
  @Type(Sample)
  sample: Sample = new Sample(); // 错误用法,不能用在自定义组件中
  build() {
  }
}
3.2 不支持某些类型
  • 不支持 collections.Setcollections.Map 等集合类型。
  • 不支持非内置类型,如 PixelMapNativePointerArrayList 等原生类型。
  • 不支持简单类型,如 stringnumberboolean 等。

四. 实践探索

@Type 通常与 PersistenceV2 结合使用,用于实现复杂对象的持久化。

import { Type, PersistenceV2 } from '@kit.ArkUI';

@ObservedV2
class SampleChild {
  @Trace p1: number = 0;
  p2: number = 10;
}

@ObservedV2
export class Sample {
  @Type(SampleChild) // 标记属性 f 的类型为 SampleChild
  @Trace f: SampleChild = new SampleChild();
}

@Entry
@ComponentV2
struct Page {
  prop: Sample = PersistenceV2.connect(Sample, () => new Sample())!;

  build() {
    Column({ space: 20 }) {
      Text(`Page1 add 1 to prop.p1: ${this.prop.f.p1}`)
        .onClick(() => {
          this.prop.f.p1++;  
        })
    }
    .width('100%')
  }
}

五.参考

  • 鸿蒙官方文档

你可能感兴趣的:(harmonyos,华为)