状态管理之复杂对象

        前面我们学习的@State、@Prop、@Link、@Provide、@Consume这些装饰器都只能更新对象的直接赋值、对象属性赋值;如果对象的属性又是一个对象,也就是嵌套对象,那么对嵌套对象的属性的更新是不会被观察到的,所以复杂状态管理用于解决该问题。

        对于复杂对象可以用@ObjectLink、@Observed解决嵌套对象的更新,二维数组,或者数组项class,或者class的属性是class,他们的第二层的属性变化可以用该方式解决。

1、概述

        @ObjectLink和@Observed类装饰器用于在涉及嵌套对象或数组的场景中进行双向数据同步:

  • 被@Observed装饰的类,可以被观察到属性的变化;
  • 子组件中@ObjectLink装饰器装饰的状态变量用于接收@Observed装饰的类的实例,和父组件中对应的状态变量建立双向数据绑定。这个实例可以是数组中的被@Observed装饰的项,或者是class object中的属性,这个属性同样也需要被@Observed装饰。
  • 单独使用@Observed是没有任何作用的,需要搭配@ObjectLink或者@Prop使用。
  • 使用@Observed装饰class会改变class原始的原型链,@Observed和其他类装饰器装饰同一个class可能会带来问题。
  • @ObjectLink装饰器不能在@Entry装饰的自定义组件中使用。
  • @ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。同时被装饰的变量不允许有初始值,初值必需从父组件初始化。

2、观察变化和行为表现 

        @Observed装饰的类,如果其属性为非简单类型,比如class、Object或者数组,也需要被@Observed装饰,否则将观察不到其属性的变化。

class ClassA {
  public c: number;

  constructor(c: number) {
    this.c = c;
  }
}

@Observed
class ClassB {
  public a: ClassA;
  public b: number;

  constructor(a: ClassA, b: number) {
    this.a = a;
    this.b = b;
  }
}

        以上示例中,ClassB被@Observed装饰,其成员变量的赋值的变化是可以被观察到的,但对于ClassA,没有被@Observed装饰,其属性的修改不能被观察到。

@ObjectLink b: ClassB

// 赋值变化可以被观察到
this.b.a = new ClassA(5)
this.b.b = 5

// ClassA没有被@Observed装饰,其属性的变化观察不到
this.b.a.c = 5

        @ObjectLink:@ObjectLink只能接收被@Observed装饰class的实例,可以观察到:

  • 其属性的数值的变化,其中属性是指Object.keys(observedObject)返回的所有属性
  • 如果数据源是数组,则可以观察到数组item的替换,如果数据源是class,可观察到class的属性的变化。

3、框架行为

  1. 初始渲染:
    1. @Observed装饰的class的实例会被不透明的代理对象包装,代理了class上的属性的setter和getter方法
    2. 子组件中@ObjectLink装饰的从父组件初始化,接收被@Observed装饰的class的实例,@ObjectLink的包装类会将自己注册给@Observed class。
  2. 属性更新:当@Observed装饰的class属性改变时,会走到代理的setter和getter,然后遍历依赖它的@ObjectLink包装类,通知数据更新。

4、嵌套对象


let NextID: number = 1;

/**
 * @Observed 使ClassA属性的变化能被观察到
 */
@Observed
class ClassA {
  public id: number;
  public c: number;

  constructor(c: number) {
    this.id = NextID++;
    this.c = c;
  }
}

@Observed
class ClassB {
  public a: ClassA;

  constructor(a: ClassA) {
    this.a = a;
  }
}

@Component
struct ViewA {
  label: string = 'ViewA1';
  @ObjectLink a: ClassA;

  build() {
    Row() {
      Button(`ViewA [${this.label}] this.a.c=${this.a.c} +1`)
        .onClick(() => {
          this.a.c += 1;
        })
    }
  }
}

/**
 * 嵌套对象变化监听
 */
@Entry
@Component
struct NestObjectDemoPage {
  @State b: ClassB = new ClassB(new ClassA(0));

  build() {
    Column({ space: 10 }) {
      ViewA({ label: 'ViewA #1', a: this.b.a })
      ViewA({ label: 'ViewA #2', a: this.b.a })

      Button(`ViewB: this.b.a.c+= 1`)
        .onClick(() => {
          //嵌套属性变化
          this.b.a.c += 1;
        })
      Button(`ViewB: this.b.a = new ClassA(0)`)
        .onClick(() => {
          //属性对象赋值
          this.b.a = new ClassA(0);
        })
      Button(`ViewB: this.b = new ClassB(ClassA(0))`)
        .onClick(() => {
          //对象赋值
          this.b = new ClassB(new ClassA(0));
        })
    }.margin({top: 48})
  }
}

        

        该示例演示了对象赋值、对象属性赋值、嵌套对象属性赋值的行为观察,这些行为都能及时的观察到并触发UI更新。 

5、对象数组

// objectLinkNestedObjects.ets
let id: number = 1;

/**
 * @Observed 使ClassA2属性的变化能被观察到
 */
@Observed
class ClassA2 {
  public id: number;
  public c: number;

  constructor(c: number) {
    this.id = id++;
    this.c = c;
  }
}

@Component
struct ViewA2 {
  // 子组件ViewA的@ObjectLink的类型是ClassA
  @ObjectLink a: ClassA2;
  label: string = 'ViewA1';

  build() {
    Row() {
      Button(`ViewA [${this.label}] this.a.c = ${this.a.c} +1`)
        .onClick(() => {
          this.a.c += 1;
        })
    }
  }
}

/**
 * 对象数组变化监听
 */
@Entry
@Component
struct ObjectArrayDemoPage {
  // ViewB中有@State装饰的ClassA[]
  @State arrA: ClassA2[] = [new ClassA2(0), new ClassA2(0)];

  build() {
    Column({ space: 10 }) {
      ForEach(this.arrA,
        (item: ClassA2) => {
          ViewA2({ label: `#${item.id}`, a: item })
        },
        (item) => item.id.toString()
      )
      // 使用@State装饰的数组的数组项初始化@ObjectLink,其中数组项是被@Observed装饰的ClassA的实例
      ViewA2({ label: `ViewA this.arrA[first]`, a: this.arrA[0] })
      ViewA2({ label: `ViewA this.arrA[last]`, a: this.arrA[this.arrA.length-1] })

      Button(`ViewB: reset array`)
        .onClick(() => {
          //数组赋值
          this.arrA = [new ClassA2(0), new ClassA2(0)];
        })
      Button(`ViewB: push`)
        .onClick(() => {
          //数组的变化[在数组末尾加一个元素]
          this.arrA.push(new ClassA2(0))
        })
      Button(`ViewB: shift`)
        .onClick(() => {
          //数组的变化[在数组头部删除一个元素]
          this.arrA.shift()
        })
      Button(`ViewB: chg item property in middle`)
        .onClick(() => {
          //数组中对象属性的赋值
          this.arrA[Math.floor(this.arrA.length / 2)].c = 10;
        })
      Button(`ViewB: chg item object in middle`)
        .onClick(() => {
          //对象数组的赋值
          this.arrA[Math.floor(this.arrA.length / 2)] = new ClassA2(11);
        })
    }.margin({top: 48})
  }
}

     案例分析:

  • this.arrA[Math.floor(this.arrA.length/2)] = new ClassA(..) :该状态变量的改变触发2次更新:
    1. ForEach:数组项的赋值导致ForEach的itemGenerator被修改,因此数组项被识别为有更改,ForEach的item builder将执行,创建新的ViewA组件实例。
    2. ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] }):上述更改改变了数组中第一个元素,所以绑定this.arrA[0]的ViewA将被更新;
  • this.arrA.push(new ClassA(0)) : 将触发2次不同效果的更新:
    1. ForEach:新添加的ClassA对象对于ForEach是未知的itemGenerator,ForEach的item builder将执行,创建新的ViewA组件实例。
    2. ViewA({ label: `ViewA this.arrA[last]`, a: this.arrA[this.arrA.length-1] }):数组的最后一项有更改,因此引起第二个ViewA的实例的更改。对于ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] }),数组的更改并没有触发一个数组项更改的改变,所以第一个ViewA不会刷新。
  • this.arrA[Math.floor(this.arrA.length/2)].c:@State无法观察到第二层的变化,但是ClassA被@Observed装饰,ClassA的属性的变化将被@ObjectLink观

6、二维数组

@Observed
class StringArray extends Array<String> {
}

@Component
struct ItemPage {
  @ObjectLink
  itemArr: StringArray;

  private scroller: Scroller = new Scroller()
  build() {
    Scroll(this.scroller) {
      Row() {
        Text('ItemPage')
          .width(100).height(100)

        ForEach(this.itemArr,
          item => {
            Text(item)
              .width(100).height(100)
          },
          item => item
        )
      }
    }.scrollable(ScrollDirection.Horizontal)
  }
}

/**
 * 二维数组变化监听,[bug]发现有性能问题
 */
@Entry
@Component
struct NestedObjectDemo2Page {
  @State arr: Array<StringArray> = [new StringArray(), new StringArray(), new StringArray()];

  build() {
    Column() {
      ItemPage({ itemArr: this.arr[0] })
      ItemPage({ itemArr: this.arr[1] })
      ItemPage({ itemArr: this.arr[2] })

      Divider()

      ForEach(this.arr,
        (itemArr: StringArray, index: number) => {
          ItemPage({ itemArr: itemArr })
        },
        itemArr => itemArr[0]
      )

      Divider()

      Button('update')
        .onClick(() => {
          console.error('Update all items in arr');
          if (this.arr[0][0] !== undefined) {
            // 正常情况下需要有一个真实的ID来与ForEach一起使用,但此处没有
            // 因此需要确保推送的字符串是唯一的。
            this.arr[0].push(`${this.arr[0].slice(-1).pop()}${this.arr[0].slice(-1).pop()}`);
            this.arr[1].push(`${this.arr[1].slice(-1).pop()}${this.arr[1].slice(-1).pop()}`);
            this.arr[2].push(`${this.arr[2].slice(-1).pop()}${this.arr[2].slice(-1).pop()}`);
          } else {
            this.arr[0].push('Hello');
            this.arr[1].push('World');
            this.arr[2].push('!');
          }
        })
    }.margin({top: 48})
  }
}

        使用new StringArray()来构造StringArray的实例,new运算符使得@Observed生效,@Observed观察到StringArray的属性变化。

        声明一个从Array扩展的类class StringArray extends Array<String> {},并创建StringArray的实例。@Observed装饰的类需要使用new运算符来构建class实例。

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值