1# \@Observed装饰器和\@ObjectLink装饰器:嵌套类对象属性变化
2
3
4上文所述的装饰器仅能观察到第一层的变化,但是在实际应用开发中,应用会根据开发需要,封装自己的数据模型。对于多层嵌套的情况,比如二维数组,或者数组项class,或者class的属性是class,他们的第二层的属性变化是无法观察到的。这就引出了\@Observed/\@ObjectLink装饰器。
5
6
7> **说明:**
8>
9> 从API version 9开始,这两个装饰器支持在ArkTS卡片中使用。
10>
11> 从API version 11开始,这两个装饰器支持在原子化服务中使用。
12
13## 概述
14
15\@ObjectLink和\@Observed类装饰器用于在涉及嵌套对象或数组的场景中进行双向数据同步:
16
17- 被\@Observed装饰的类,可以被观察到属性的变化;
18
19- 子组件中\@ObjectLink装饰器装饰的状态变量用于接收\@Observed装饰的类的实例,和父组件中对应的状态变量建立双向数据绑定。这个实例可以是数组中的被\@Observed装饰的项,或者是class object中的属性,这个属性同样也需要被\@Observed装饰。
20
21- \@Observed用于嵌套类场景中,观察对象类属性变化,要配合自定义组件使用(示例详见[嵌套对象](#嵌套对象)),如果要做数据双/单向同步,需要搭配\@ObjectLink或者\@Prop使用(示例详见[\@Prop与\@ObjectLink的差异](#prop与objectlink的差异))。
22
23
24## 限制条件
25
26- 使用\@Observed装饰class会改变class原始的原型链,\@Observed和其他类装饰器装饰同一个class可能会带来问题。
27
28- \@ObjectLink装饰器不能在\@Entry装饰的自定义组件中使用。
29
30
31## 装饰器说明
32
33| \@Observed类装饰器 | 说明                                |
34| -------------- | --------------------------------- |
35| 装饰器参数          | 无                                 |
36| 类装饰器           | 装饰class。需要放在class的定义前,使用new创建类对象。 |
37
38| \@ObjectLink变量装饰器 | 说明                                       |
39| ----------------- | ---------------------------------------- |
40| 装饰器参数             | 无                                        |
41| 允许装饰的变量类型         | 必须为被\@Observed装饰的class实例,必须指定类型。<br/>不支持简单类型,可以使用[\@Prop](arkts-prop.md)。<br/>支持继承Date、[Array](#二维数组)的class实例,API11及以上支持继承[Map](#继承map类)、[Set](#继承set类)的class实例。示例见[观察变化](#观察变化)。<br/>API11及以上支持\@Observed装饰类和undefined或null组成的联合类型,比如ClassA \| ClassB, ClassA \| undefined 或者 ClassA \| null, 示例见[@ObjectLink支持联合类型](#objectlink支持联合类型)。<br/>\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 |
42| 被装饰变量的初始值         | 不允许。                                     |
43
44\@ObjectLink装饰的数据为可读示例。
45
46
47```ts
48// 允许@ObjectLink装饰的数据属性赋值
49this.objLink.a= ...
50// 不允许@ObjectLink装饰的数据自身赋值
51this.objLink= ...
52```
53
54> **说明:**
55>
56> \@ObjectLink装饰的变量不能被赋值,如果要使用赋值操作,请使用[@Prop](arkts-prop.md)。
57>
58> - \@Prop装饰的变量和数据源的关系是是单向同步,\@Prop装饰的变量在本地拷贝了数据源,所以它允许本地更改,如果父组件中的数据源有更新,\@Prop装饰的变量本地的修改将被覆盖;
59>
60> - \@ObjectLink装饰的变量和数据源的关系是双向同步,\@ObjectLink装饰的变量相当于指向数据源的指针。禁止对\@ObjectLink装饰的变量赋值,如果一旦发生\@ObjectLink装饰的变量的赋值,则同步链将被打断。因为\@ObjectLink装饰的变量通过数据源(Object)引用来初始化。对于实现双向数据同步的@ObjectLink,赋值相当于更新父组件中的数组项或者class的属性,TypeScript/JavaScript不能实现,会发生运行时报错。
61
62
63## 变量的传递/访问规则说明
64
65| \@ObjectLink传递/访问 | 说明                                       |
66| ----------------- | ---------------------------------------- |
67| 从父组件初始化           | 必须指定。<br/>初始化\@ObjectLink装饰的变量必须同时满足以下场景:<br/>-&nbsp;类型必须是\@Observed装饰的class。<br/>-&nbsp;初始化的数值需要是数组项,或者class的属性。<br/>-&nbsp;同步源的class或者数组必须是[\@State](./arkts-state.md),[\@Link](./arkts-link.md),[\@Provide](./arkts-provide-and-consume.md),[\@Consume](./arkts-provide-and-consume.md)或者\@ObjectLink装饰的数据。<br/>同步源是数组项的示例请参考[对象数组](#对象数组)。初始化的class的示例请参考[嵌套对象](#嵌套对象)。 |
68| 与源对象同步            | 双向。                                      |
69| 可以初始化子组件          | 允许,可用于初始化常规变量、\@State、\@Link、\@Prop、\@Provide |
70
71
72  **图1** 初始化规则图示  
73
74
75![zh-cn_image_0000001502255262](figures/zh-cn_image_0000001502255262.png)
76
77
78## 观察变化和行为表现
79
80
81### 观察变化
82
83\@Observed装饰的类,如果其属性为非简单类型,比如class、Object或者数组,也需要被\@Observed装饰,否则将观察不到其属性的变化。
84
85
86```ts
87class Child {
88  public num: number;
89
90  constructor(num: number) {
91    this.num = num;
92  }
93}
94
95@Observed
96class Parent {
97  public child: Child;
98  public count: number;
99
100  constructor(child: Child, count: number) {
101    this.child = child;
102    this.count = count;
103  }
104}
105```
106
107以上示例中,Parent被\@Observed装饰,其成员变量的赋值的变化是可以被观察到的,但对于Child,没有被\@Observed装饰,其属性的修改不能被观察到。
108
109
110```ts
111@ObjectLink parent: Parent
112
113// 赋值变化可以被观察到
114this.parent.child = new Child(5)
115this.parent.count = 5
116
117// ClassA没有被@Observed装饰,其属性的变化观察不到
118this.parent.child.num = 5
119```
120
121\@ObjectLink:\@ObjectLink只能接收被\@Observed装饰class的实例,推荐设计单独的自定义组件来渲染每一个数组或对象。此时,对象数组或嵌套对象(属性是对象的对象称为嵌套对象)需要两个自定义组件,一个自定义组件呈现外部数组/对象,另一个自定义组件呈现嵌套在数组/对象内的类对象。可以观察到:
122
123- 其属性的数值的变化,其中属性是指Object.keys(observedObject)返回的所有属性,示例请参考[嵌套对象](#嵌套对象)。
124
125- 如果数据源是数组,则可以观察到数组item的替换,如果数据源是class,可观察到class的属性的变化,示例请参考[对象数组](#对象数组)。
126
127继承Date的class时,可以观察到Date整体的赋值,同时可通过调用Date的接口`setFullYear`, `setMonth`, `setDate`, `setHours`, `setMinutes`, `setSeconds`, `setMilliseconds`, `setTime`, `setUTCFullYear`, `setUTCMonth`, `setUTCDate`, `setUTCHours`, `setUTCMinutes`, `setUTCSeconds`, `setUTCMilliseconds` 更新Date的属性。
128
129```ts
130@Observed
131class DateClass extends Date {
132  constructor(args: number | string) {
133    super(args)
134  }
135}
136
137@Observed
138class NewDate {
139  public data: DateClass;
140
141  constructor(data: DateClass) {
142    this.data = data;
143  }
144}
145
146@Component
147struct Child {
148  label: string = 'date';
149  @ObjectLink data: DateClass;
150
151  build() {
152    Column() {
153      Button(`child increase the day by 1`)
154        .onClick(() => {
155          this.data.setDate(this.data.getDate() + 1);
156        })
157      DatePicker({
158        start: new Date('1970-1-1'),
159        end: new Date('2100-1-1'),
160        selected: this.data
161      })
162    }
163  }
164}
165
166@Entry
167@Component
168struct Parent {
169  @State newData: NewDate = new NewDate(new DateClass('2023-1-1'));
170
171  build() {
172    Column() {
173      Child({ label: 'date', data: this.newData.data })
174
175      Button(`parent update the new date`)
176        .onClick(() => {
177          this.newData.data = new DateClass('2023-07-07');
178        })
179      Button(`ViewB: this.newData = new NewDate(new DateClass('2023-08-20'))`)
180        .onClick(() => {
181          this.newData = new NewDate(new DateClass('2023-08-20'));
182        })
183    }
184  }
185}
186```
187
188继承Map的class时,可以观察到Map整体的赋值,同时可通过调用Map的接口`set`, `clear`, `delete` 更新Map的值。详见[继承Map类](#继承map类)。
189
190继承Set的class时,可以观察到Set整体的赋值,同时可通过调用Set的接口`add`, `clear`, `delete` 更新Set的值。详见[继承Set类](#继承set类)。
191
192
193### 框架行为
194
1951. 初始渲染:
196   1. \@Observed装饰的class的实例会被不透明的代理对象包装,代理了class上的属性的setter和getter方法
197   2. 子组件中\@ObjectLink装饰的从父组件初始化,接收被\@Observed装饰的class的实例,\@ObjectLink的包装类会将自己注册给\@Observed class。
198
1992. 属性更新:当\@Observed装饰的class属性改变时,会走到代理的setter和getter,然后遍历依赖它的\@ObjectLink包装类,通知数据更新。
200
201
202## 使用场景
203
204
205### 嵌套对象
206
207> **说明:**
208>
209> NextID是用来在[ForEach循环渲染](./arkts-rendering-control-foreach.md)过程中,为每个数组元素生成一个唯一且持久的键值,用于标识对应的组件。
210
211
212```ts
213// objectLinkNestedObjects.ets
214let NextID: number = 1;
215
216@Observed
217class Bag {
218  public id: number;
219  public size: number;
220
221  constructor(size: number) {
222    this.id = NextID++;
223    this.size = size;
224  }
225}
226
227@Observed
228class User {
229  public bag: Bag;
230
231  constructor(bag: Bag) {
232    this.bag = bag;
233  }
234}
235
236@Observed
237class Book {
238  public bookName: BookName;
239
240  constructor(bookName: BookName) {
241    this.bookName = bookName;
242  }
243}
244
245@Observed
246class BookName extends Bag {
247  public nameSize: number;
248
249  constructor(nameSize: number) {
250    // 调用父类方法对nameSize进行处理
251    super(nameSize);
252    this.nameSize = nameSize;
253  }
254}
255
256@Component
257struct ViewA {
258  label: string = 'ViewA';
259  @ObjectLink bag: Bag;
260
261  build() {
262    Column() {
263      Text(`ViewA [${this.label}] this.bag.size = ${this.bag.size}`)
264        .fontColor('#ffffffff')
265        .backgroundColor('#ff3d9dba')
266        .width(320)
267        .height(50)
268        .borderRadius(25)
269        .margin(10)
270        .textAlign(TextAlign.Center)
271      Button(`ViewA: this.bag.size add 1`)
272        .width(320)
273        .backgroundColor('#ff17a98d')
274        .margin(10)
275        .onClick(() => {
276          this.bag.size += 1;
277        })
278    }
279  }
280}
281
282@Component
283struct ViewC {
284  label: string = 'ViewC1';
285  @ObjectLink bookName: BookName;
286
287  build() {
288    Row() {
289      Column() {
290        Text(`ViewC [${this.label}] this.bookName.size = ${this.bookName.size}`)
291          .fontColor('#ffffffff')
292          .backgroundColor('#ff3d9dba')
293          .width(320)
294          .height(50)
295          .borderRadius(25)
296          .margin(10)
297          .textAlign(TextAlign.Center)
298        Button(`ViewC: this.bookName.size add 1`)
299          .width(320)
300          .backgroundColor('#ff17a98d')
301          .margin(10)
302          .onClick(() => {
303            this.bookName.size += 1;
304            console.log('this.bookName.size:' + this.bookName.size)
305          })
306      }
307      .width(320)
308    }
309  }
310}
311
312@Entry
313@Component
314struct ViewB {
315  @State user: User = new User(new Bag(0));
316  @State child: Book = new Book(new BookName(0));
317
318  build() {
319    Column() {
320      ViewA({ label: 'ViewA #1', bag: this.user.bag })
321        .width(320)
322      ViewC({ label: 'ViewC #3', bookName: this.child.bookName })
323        .width(320)
324      Button(`ViewB: this.child.bookName.size add 10`)
325        .width(320)
326        .backgroundColor('#ff17a98d')
327        .margin(10)
328        .onClick(() => {
329          this.child.bookName.size += 10
330          console.log('this.child.bookName.size:' + this.child.bookName.size)
331        })
332      Button(`ViewB: this.user.bag = new Bag(10)`)
333        .width(320)
334        .backgroundColor('#ff17a98d')
335        .margin(10)
336        .onClick(() => {
337          this.user.bag = new Bag(10);
338        })
339      Button(`ViewB: this.user = new User(new Bag(20))`)
340        .width(320)
341        .backgroundColor('#ff17a98d')
342        .margin(10)
343        .onClick(() => {
344          this.user = new User(new Bag(20));
345        })
346    }
347  }
348}
349```
350
351![Observed_ObjectLink_nested_object](figures/Observed_ObjectLink_nested_object.gif)
352
353被@Observed装饰的BookName类,可以观测到继承基类的属性的变化。
354
355
356ViewB中的事件句柄:
357
358
359- this.user.bag = new Bag(10) 和this.user = new User(new Bag(20)): 对@State装饰的变量size和其属性的修改。
360
361- this.child.bookName.size += ... :该变化属于第二层的变化,@State无法观察到第二层的变化,但是Bag被\@Observed装饰,Bag的属性size的变化可以被\@ObjectLink观察到。
362
363
364ViewC中的事件句柄:
365
366
367- this.bookName.size += 1:对\@ObjectLink变量size的修改,将触发Button组件的刷新。\@ObjectLink和\@Prop不同,\@ObjectLink不拷贝来自父组件的数据源,而是在本地构建了指向其数据源的引用。
368
369- \@ObjectLink变量是只读的,this.bookName = new bookName(...)是不允许的,因为一旦赋值操作发生,指向数据源的引用将被重置,同步将被打断。
370
371
372### 对象数组
373
374对象数组是一种常用的数据结构。以下示例展示了数组对象的用法。
375
376
377```ts
378let NextID: number = 1;
379
380@Observed
381class Info {
382  public id: number;
383  public info: number;
384
385  constructor(info: number) {
386    this.id = NextID++;
387    this.info = info;
388  }
389}
390
391@Component
392struct Child {
393  // 子组件Child的@ObjectLink的类型是Info
394  @ObjectLink info: Info;
395  label: string = 'ViewChild';
396
397  build() {
398    Row() {
399      Button(`ViewChild [${this.label}] this.info.info = ${this.info ? this.info.info : "undefined"}`)
400        .width(320)
401        .margin(10)
402        .onClick(() => {
403          this.info.info += 1;
404        })
405    }
406  }
407}
408
409@Entry
410@Component
411struct Parent {
412  // Parent中有@State装饰的Info[]
413  @State arrA: Info[] = [new Info(0), new Info(0)];
414
415  build() {
416    Column() {
417      ForEach(this.arrA,
418        (item: Info) => {
419          Child({ label: `#${item.id}`, info: item })
420        },
421        (item: Info): string => item.id.toString()
422      )
423      // 使用@State装饰的数组的数组项初始化@ObjectLink,其中数组项是被@Observed装饰的Info的实例
424      Child({ label: `ViewChild this.arrA[first]`, info: this.arrA[0] })
425      Child({ label: `ViewChild this.arrA[last]`, info: this.arrA[this.arrA.length-1] })
426
427      Button(`ViewParent: reset array`)
428        .width(320)
429        .margin(10)
430        .onClick(() => {
431          this.arrA = [new Info(0), new Info(0)];
432        })
433      Button(`ViewParent: push`)
434        .width(320)
435        .margin(10)
436        .onClick(() => {
437          this.arrA.push(new Info(0))
438        })
439      Button(`ViewParent: shift`)
440        .width(320)
441        .margin(10)
442        .onClick(() => {
443          if (this.arrA.length > 0) {
444            this.arrA.shift()
445          } else {
446            console.log("length <= 0")
447          }
448        })
449      Button(`ViewParent: item property in middle`)
450        .width(320)
451        .margin(10)
452        .onClick(() => {
453          this.arrA[Math.floor(this.arrA.length / 2)].info = 10;
454        })
455      Button(`ViewParent: item property in middle`)
456        .width(320)
457        .margin(10)
458        .onClick(() => {
459          this.arrA[Math.floor(this.arrA.length / 2)] = new Info(11);
460        })
461    }
462  }
463}
464```
465
466![Observed_ObjectLink_object_array](figures/Observed_ObjectLink_object_array.gif)
467
468- this.arrA[Math.floor(this.arrA.length/2)] = new Info(..) :该状态变量的改变触发2次更新:
469  1. ForEach:数组项的赋值导致ForEach的[itemGenerator](../reference/apis-arkui/arkui-ts/ts-rendering-control-foreach.md)被修改,因此数组项被识别为有更改,ForEach的item builder将执行,创建新的Child组件实例。
470  2. Child({ label: `ViewChild this.arrA[last]`, info: this.arrA[this.arrA.length-1] }):上述更改改变了数组中第二个元素,所以绑定this.arrA[1]的Child将被更新。
471
472- this.arrA.push(new Info(0)) : 将触发2次不同效果的更新:
473  1. ForEach:新添加的Info对象对于ForEach是未知的[itemGenerator](../reference/apis-arkui/arkui-ts/ts-rendering-control-foreach.md),ForEach的item builder将执行,创建新的Child组件实例。
474  2. Child({ label: `ViewChild this.arrA[last]`, info: this.arrA[this.arrA.length-1] }):数组的最后一项有更改,因此引起第二个Child的实例的更改。对于Child({ label: `ViewChild this.arrA[first]`, info: this.arrA[0] }),数组的更改并没有触发一个数组项更改的改变,所以第一个Child不会刷新。
475
476- this.arrA[Math.floor(this.arrA.length/2)].info:@State无法观察到第二层的变化,但是Info被\@Observed装饰,Info的属性的变化将被\@ObjectLink观察到。
477
478
479### 二维数组
480
481使用\@Observed观察二维数组的变化。可以声明一个被\@Observed装饰的继承Array的子类。
482
483
484```ts
485@Observed
486class StringArray extends Array<string> {
487}
488```
489
490使用new StringArray()来构造StringArray的实例,new运算符使得\@Observed生效,\@Observed观察到StringArray的属性变化。
491
492声明一个从Array扩展的类class StringArray extends Array&lt;string&gt; {},并创建StringArray的实例。\@Observed装饰的类需要使用new运算符来构建class实例。
493
494
495```ts
496@Observed
497class StringArray extends Array<string> {
498}
499
500@Component
501struct ItemPage {
502  @ObjectLink itemArr: StringArray;
503
504  build() {
505    Row() {
506      Text('ItemPage')
507        .width(100).height(100)
508
509      ForEach(this.itemArr,
510        (item: string | Resource) => {
511          Text(item)
512            .width(100).height(100)
513        },
514        (item: string) => item
515      )
516    }
517  }
518}
519
520@Entry
521@Component
522struct IndexPage {
523  @State arr: Array<StringArray> = [new StringArray(), new StringArray(), new StringArray()];
524
525  build() {
526    Column() {
527      ItemPage({ itemArr: this.arr[0] })
528      ItemPage({ itemArr: this.arr[1] })
529      ItemPage({ itemArr: this.arr[2] })
530      Divider()
531
532
533      ForEach(this.arr,
534        (itemArr: StringArray) => {
535          ItemPage({ itemArr: itemArr })
536        },
537        (itemArr: StringArray) => itemArr[0]
538      )
539
540      Divider()
541
542      Button('update')
543        .onClick(() => {
544          console.error('Update all items in arr');
545          if ((this.arr[0] as StringArray)[0] !== undefined) {
546            // 正常情况下需要有一个真实的ID来与ForEach一起使用,但此处没有
547            // 因此需要确保推送的字符串是唯一的。
548            this.arr[0].push(`${this.arr[0].slice(-1).pop()}${this.arr[0].slice(-1).pop()}`);
549            this.arr[1].push(`${this.arr[1].slice(-1).pop()}${this.arr[1].slice(-1).pop()}`);
550            this.arr[2].push(`${this.arr[2].slice(-1).pop()}${this.arr[2].slice(-1).pop()}`);
551          } else {
552            this.arr[0].push('Hello');
553            this.arr[1].push('World');
554            this.arr[2].push('!');
555          }
556        })
557    }
558  }
559}
560```
561
562![Observed_ObjectLink_2D_array](figures/Observed_ObjectLink_2D_array.gif)
563
564### 继承Map类
565
566> **说明:**
567>
568> 从API version 11开始,\@ObjectLink支持\@Observed装饰Map类型和继承Map类的类型。
569
570在下面的示例中,myMap类型为MyMap\<number, string\>,点击Button改变myMap的属性,视图会随之刷新。
571
572```ts
573@Observed
574class Info {
575  public info: MyMap<number, string>;
576
577  constructor(info: MyMap<number, string>) {
578    this.info = info;
579  }
580}
581
582
583@Observed
584export class MyMap<K, V> extends Map<K, V> {
585  public name: string;
586
587  constructor(name?: string, args?: [K, V][]) {
588    super(args);
589    this.name = name ? name : "My Map";
590  }
591
592  getName() {
593    return this.name;
594  }
595}
596
597@Entry
598@Component
599struct MapSampleNested {
600  @State message: Info = new Info(new MyMap("myMap", [[0, "a"], [1, "b"], [3, "c"]]));
601
602  build() {
603    Row() {
604      Column() {
605        MapSampleNestedChild({ myMap: this.message.info })
606      }
607      .width('100%')
608    }
609    .height('100%')
610  }
611}
612
613@Component
614struct MapSampleNestedChild {
615  @ObjectLink myMap: MyMap<number, string>
616
617  build() {
618    Row() {
619      Column() {
620        ForEach(Array.from(this.myMap.entries()), (item: [number, string]) => {
621          Text(`${item[0]}`).fontSize(30)
622          Text(`${item[1]}`).fontSize(30)
623          Divider().strokeWidth(5)
624        })
625
626        Button('set new one')
627          .width(200)
628          .margin(10)
629          .onClick(() => {
630            this.myMap.set(4, "d")
631          })
632        Button('clear')
633          .width(200)
634          .margin(10)
635          .onClick(() => {
636            this.myMap.clear()
637          })
638        Button('replace the first one')
639          .width(200)
640          .margin(10)
641          .onClick(() => {
642            this.myMap.set(0, "aa")
643          })
644        Button('delete the first one')
645          .width(200)
646          .margin(10)
647          .onClick(() => {
648            this.myMap.delete(0)
649          })
650      }
651      .width('100%')
652    }
653    .height('100%')
654  }
655}
656```
657
658![Observed_ObjectLink_inherit_map](figures/Observed_ObjectLink_inherit_map.gif)
659
660### 继承Set类
661
662> **说明:**
663>
664> 从API version 11开始,\@ObjectLink支持\@Observed装饰Set类型和继承Set类的类型。
665
666在下面的示例中,mySet类型为MySet\<number\>,点击Button改变mySet的属性,视图会随之刷新。
667
668```ts
669@Observed
670class Info {
671  public info: MySet<number>;
672
673  constructor(info: MySet<number>) {
674    this.info = info;
675  }
676}
677
678
679@Observed
680export class MySet<T> extends Set<T> {
681  public name: string;
682
683  constructor(name?: string, args?: T[]) {
684    super(args);
685    this.name = name ? name : "My Set";
686  }
687
688  getName() {
689    return this.name;
690  }
691}
692
693@Entry
694@Component
695struct SetSampleNested {
696  @State message: Info = new Info(new MySet("Set", [0, 1, 2, 3, 4]));
697
698  build() {
699    Row() {
700      Column() {
701        SetSampleNestedChild({ mySet: this.message.info })
702      }
703      .width('100%')
704    }
705    .height('100%')
706  }
707}
708
709@Component
710struct SetSampleNestedChild {
711  @ObjectLink mySet: MySet<number>
712
713  build() {
714    Row() {
715      Column() {
716        ForEach(Array.from(this.mySet.entries()), (item: [number, number]) => {
717          Text(`${item}`).fontSize(30)
718          Divider()
719        })
720        Button('set new one')
721          .width(200)
722          .margin(10)
723          .onClick(() => {
724            this.mySet.add(5)
725          })
726        Button('clear')
727          .width(200)
728          .margin(10)
729          .onClick(() => {
730            this.mySet.clear()
731          })
732        Button('delete the first one')
733          .width(200)
734          .margin(10)
735          .onClick(() => {
736            this.mySet.delete(0)
737          })
738      }
739      .width('100%')
740    }
741    .height('100%')
742  }
743}
744```
745
746![Observed_ObjectLink_inherit_set](figures/Observed_ObjectLink_inherit_set.gif)
747
748## ObjectLink支持联合类型
749
750@ObjectLink支持@Observed装饰类和undefined或null组成的联合类型,在下面的示例中,count类型为Source | Data | undefined,点击父组件Parent中的Button改变count的属性或者类型,Child中也会对应刷新。
751
752```ts
753@Observed
754class Source {
755  public source: number;
756
757  constructor(source: number) {
758    this.source = source;
759  }
760}
761
762@Observed
763class Data {
764  public data: number;
765
766  constructor(data: number) {
767    this.data = data;
768  }
769}
770
771@Entry
772@Component
773struct Parent {
774  @State count: Source | Data | undefined = new Source(10)
775
776  build() {
777    Column() {
778      Child({ count: this.count })
779
780      Button('change count property')
781        .onClick(() => {
782          // 判断count的类型,做属性的更新
783          if (this.count instanceof Source) {
784            this.count.source += 1
785          } else if (this.count instanceof Data) {
786            this.count.data += 1
787          } else {
788            console.info('count is undefined, cannot change property')
789          }
790        })
791
792      Button('change count to Source')
793        .onClick(() => {
794          // 赋值为Source的实例
795          this.count = new Source(100)
796        })
797
798      Button('change count to Data')
799        .onClick(() => {
800          // 赋值为Data的实例
801          this.count = new Data(100)
802        })
803
804      Button('change count to undefined')
805        .onClick(() => {
806          // 赋值为undefined
807          this.count = undefined
808        })
809    }.width('100%')
810  }
811}
812
813@Component
814struct Child {
815  @ObjectLink count: Source | Data | undefined
816
817  build() {
818    Column() {
819      Text(`count is instanceof ${this.count instanceof Source ? 'Source' :
820        this.count instanceof Data ? 'Data' : 'undefined'}`)
821        .fontSize(30)
822
823      Text(`count's property is  ${this.count instanceof Source ? this.count.source : this.count?.data}`).fontSize(15)
824
825    }.width('100%')
826  }
827}
828```
829
830![ObjectLink-support-union-types](figures/ObjectLink-support-union-types.gif)
831
832## 常见问题
833
834### 在子组件中给@ObjectLink装饰的变量赋值
835
836在子组件中给@ObjectLink装饰的变量赋值是不允许的。
837
838【反例】
839
840```ts
841@Observed
842class Info {
843  public info: number = 0;
844
845  constructor(info: number) {
846    this.info = info;
847  }
848}
849
850@Component
851struct ObjectLinkChild {
852  @ObjectLink testNum: Info;
853
854  build() {
855    Text(`ObjectLinkChild testNum ${this.testNum.info}`)
856      .onClick(() => {
857        // ObjectLink不能被赋值
858        this.testNum = new Info(47);
859      })
860  }
861}
862
863@Entry
864@Component
865struct Parent {
866  @State testNum: Info[] = [new Info(1)];
867
868  build() {
869    Column() {
870      Text(`Parent testNum ${this.testNum[0].info}`)
871        .onClick(() => {
872          this.testNum[0].info += 1;
873        })
874
875      ObjectLinkChild({ testNum: this.testNum[0] })
876    }
877  }
878}
879```
880
881点击ObjectLinkChild给\@ObjectLink装饰的变量赋值:
882
883```
884this.testNum = new Info(47); 
885```
886
887这是不允许的,对于实现双向数据同步的\@ObjectLink,赋值相当于要更新父组件中的数组项或者class的属性,这个对于 TypeScript/JavaScript是不能实现的。框架对于这种行为会发生运行时报错。
888
889【正例】
890
891```ts
892@Observed
893class Info {
894  public info: number = 0;
895
896  constructor(info: number) {
897    this.info = info;
898  }
899}
900
901@Component
902struct ObjectLinkChild {
903  @ObjectLink testNum: Info;
904
905  build() {
906    Text(`ObjectLinkChild testNum ${this.testNum.info}`)
907      .onClick(() => {
908        // 可以对ObjectLink装饰对象的属性赋值
909        this.testNum.info = 47;
910      })
911  }
912}
913
914@Entry
915@Component
916struct Parent {
917  @State testNum: Info[] = [new Info(1)];
918
919  build() {
920    Column() {
921      Text(`Parent testNum ${this.testNum[0].info}`)
922        .onClick(() => {
923          this.testNum[0].info += 1;
924        })
925
926      ObjectLinkChild({ testNum: this.testNum[0] })
927    }
928  }
929}
930```
931
932### 基础嵌套对象属性更改失效
933
934在应用开发中,有很多嵌套对象场景,例如,开发者更新了某个属性,但UI没有进行对应的更新。
935
936每个装饰器都有自己可以观察的能力,并不是所有的改变都可以被观察到,只有可以被观察到的变化才会进行UI更新。\@Observed装饰器可以观察到嵌套对象的属性变化,其他装饰器仅能观察到第一层的变化。
937
938【反例】
939
940下面的例子中,一些UI组件并不会更新。
941
942
943```ts
944class Parent {
945  parentId: number;
946
947  constructor(parentId: number) {
948    this.parentId = parentId;
949  }
950
951  getParentId(): number {
952    return this.parentId;
953  }
954
955  setParentId(parentId: number): void {
956    this.parentId = parentId;
957  }
958}
959
960class Child {
961  childId: number;
962
963  constructor(childId: number) {
964    this.childId = childId;
965  }
966
967  getChildId(): number {
968    return this.childId;
969  }
970
971  setChildId(childId: number): void {
972    this.childId = childId;
973  }
974}
975
976class Cousin extends Parent {
977  cousinId: number = 47;
978  child: Child;
979
980  constructor(parent: number, cousinId: number, child: number) {
981    super(parent);
982    this.cousinId = cousinId;
983    this.child = new Child(child);
984  }
985
986  getCousinId(): number {
987    return this.cousinId;
988  }
989
990  setCousinId(cousinId: number): void {
991    this.cousinId = cousinId;
992  }
993
994  getChild(): number {
995    return this.child.getChildId();
996  }
997
998  setChild(child: number): void {
999    return this.child.setChildId(child);
1000  }
1001}
1002
1003@Entry
1004@Component
1005struct MyView {
1006  @State cousin: Cousin = new Cousin(10, 20, 30);
1007
1008  build() {
1009    Column({ space: 10 }) {
1010      Text(`parentId: ${this.cousin.parentId}`)
1011      Button("Change Parent.parent")
1012        .onClick(() => {
1013          this.cousin.parentId += 1;
1014        })
1015
1016      Text(`cousinId: ${this.cousin.cousinId}`)
1017      Button("Change Cousin.cousinId")
1018        .onClick(() => {
1019          this.cousin.cousinId += 1;
1020        })
1021
1022      Text(`childId: ${this.cousin.child.childId}`)
1023      Button("Change Cousin.Child.childId")
1024        .onClick(() => {
1025          // 点击时上面的Text组件不会刷新
1026          this.cousin.child.childId += 1;
1027        })
1028    }
1029  }
1030}
1031```
1032
1033- 最后一个Text组件Text('child: ${this.cousin.child.childId}'),当点击该组件时UI不会刷新。 因为,\@State cousin : Cousin 只能观察到this.cousin属性的变化,比如this.cousin.parentId, this.cousin.cousinIdthis.cousin.child的变化,但是无法观察嵌套在属性中的属性,即this.cousin.child.childId(属性childId是内嵌在cousin中的对象Child的属性)。
1034
1035- 为了观察到嵌套于内部的Child的属性,需要做如下改变:
1036  - 构造一个子组件,用于单独渲染Child的实例。 该子组件可以使用\@ObjectLink child : Child或\@Prop child : Child。通常会使用\@ObjectLink,除非子组件需要对其Child对象进行本地修改。
1037  - 嵌套的Child必须用\@Observed装饰。当在Cousin中创建Child对象时(本示例中的Cousin(10, 20, 30)),它将被包装在ES6代理中,当Child属性更改时(this.cousin.child.childId += 1),该代码将修改通知到\@ObjectLink变量。
1038
1039【正例】
1040
1041以下示例使用\@Observed/\@ObjectLink来观察嵌套对象的属性更改。
1042
1043
1044```ts
1045class Parent {
1046  parentId: number;
1047
1048  constructor(parentId: number) {
1049    this.parentId = parentId;
1050  }
1051
1052  getParentId(): number {
1053    return this.parentId;
1054  }
1055
1056  setParentId(parentId: number): void {
1057    this.parentId = parentId;
1058  }
1059}
1060
1061@Observed
1062class Child {
1063  childId: number;
1064
1065  constructor(childId: number) {
1066    this.childId = childId;
1067  }
1068
1069  getChildId(): number {
1070    return this.childId;
1071  }
1072
1073  setChildId(childId: number): void {
1074    this.childId = childId;
1075  }
1076}
1077
1078class Cousin extends Parent {
1079  cousinId: number = 47;
1080  child: Child;
1081
1082  constructor(parent: number, cousinId: number, child: number) {
1083    super(parent);
1084    this.cousinId = cousinId;
1085    this.child = new Child(child);
1086  }
1087
1088  getCousinId(): number {
1089    return this.cousinId;
1090  }
1091
1092  setCousinId(cousinId: number): void {
1093    this.cousinId = cousinId;
1094  }
1095
1096  getChild(): number {
1097    return this.child.getChildId();
1098  }
1099
1100  setChild(child: number): void {
1101    return this.child.setChildId(child);
1102  }
1103}
1104
1105@Component
1106struct ViewChild {
1107  @ObjectLink child: Child;
1108
1109  build() {
1110    Column({ space: 10 }) {
1111      Text(`childId: ${this.child.getChildId()}`)
1112      Button("Change childId")
1113        .onClick(() => {
1114          this.child.setChildId(this.child.getChildId() + 1);
1115        })
1116    }
1117  }
1118}
1119
1120@Entry
1121@Component
1122struct MyView {
1123  @State cousin: Cousin = new Cousin(10, 20, 30);
1124
1125  build() {
1126    Column({ space: 10 }) {
1127      Text(`parentId: ${this.cousin.parentId}`)
1128      Button("Change Parent.parentId")
1129        .onClick(() => {
1130          this.cousin.parentId += 1;
1131        })
1132
1133      Text(`cousinId: ${this.cousin.cousinId}`)
1134      Button("Change Cousin.cousinId")
1135        .onClick(() => {
1136          this.cousin.cousinId += 1;
1137        })
1138
1139      ViewChild({ child: this.cousin.child }) // Text(`childId: ${this.cousin.child.childId}`)的替代写法
1140      Button("Change Cousin.Child.childId")
1141        .onClick(() => {
1142          this.cousin.child.childId += 1;
1143        })
1144    }
1145  }
1146}
1147```
1148
1149### 复杂嵌套对象属性更改失效
1150
1151【反例】
1152
1153以下示例创建了一个带有\@ObjectLink装饰变量的子组件,用于渲染一个含有嵌套属性的ParentCounter,用\@Observed装饰嵌套在ParentCounter中的SubCounter。
1154
1155
1156```ts
1157let nextId = 1;
1158@Observed
1159class SubCounter {
1160  counter: number;
1161  constructor(c: number) {
1162    this.counter = c;
1163  }
1164}
1165@Observed
1166class ParentCounter {
1167  id: number;
1168  counter: number;
1169  subCounter: SubCounter;
1170  incrCounter() {
1171    this.counter++;
1172  }
1173  incrSubCounter(c: number) {
1174    this.subCounter.counter += c;
1175  }
1176  setSubCounter(c: number): void {
1177    this.subCounter.counter = c;
1178  }
1179  constructor(c: number) {
1180    this.id = nextId++;
1181    this.counter = c;
1182    this.subCounter = new SubCounter(c);
1183  }
1184}
1185@Component
1186struct CounterComp {
1187  @ObjectLink value: ParentCounter;
1188  build() {
1189    Column({ space: 10 }) {
1190      Text(`${this.value.counter}`)
1191        .fontSize(25)
1192        .onClick(() => {
1193          this.value.incrCounter();
1194        })
1195      Text(`${this.value.subCounter.counter}`)
1196        .onClick(() => {
1197          this.value.incrSubCounter(1);
1198        })
1199      Divider().height(2)
1200    }
1201  }
1202}
1203@Entry
1204@Component
1205struct ParentComp {
1206  @State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1207  build() {
1208    Row() {
1209      Column() {
1210        CounterComp({ value: this.counter[0] })
1211        CounterComp({ value: this.counter[1] })
1212        CounterComp({ value: this.counter[2] })
1213        Divider().height(5)
1214        ForEach(this.counter,
1215          (item: ParentCounter) => {
1216            CounterComp({ value: item })
1217          },
1218          (item: ParentCounter) => item.id.toString()
1219        )
1220        Divider().height(5)
1221        // 第一个点击事件
1222        Text('Parent: incr counter[0].counter')
1223          .fontSize(20).height(50)
1224          .onClick(() => {
1225            this.counter[0].incrCounter();
1226            // 每次触发时自增10
1227            this.counter[0].incrSubCounter(10);
1228          })
1229        // 第二个点击事件
1230        Text('Parent: set.counter to 10')
1231          .fontSize(20).height(50)
1232          .onClick(() => {
1233            // 无法将value设置为10,UI不会刷新
1234            this.counter[0].setSubCounter(10);
1235          })
1236        Text('Parent: reset entire counter')
1237          .fontSize(20).height(50)
1238          .onClick(() => {
1239            this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1240          })
1241      }
1242    }
1243  }
1244}
1245```
1246
1247对于Text('Parent: incr counter[0].counter')的onClick事件,this.counter[0].incrSubCounter(10)调用incrSubCounter方法使SubCounter的counter值增加10,UI同步刷新。
1248
1249但是,在Text('Parent: set.counter to 10')的onClick中调用this.counter[0].setSubCounter(10),SubCounter的counter值却无法重置为10。
1250
1251incrSubCounter和setSubCounter都是同一个SubCounter的函数。在第一个点击处理时调用incrSubCounter可以正确更新UI,而第二个点击处理调用setSubCounter时却没有更新UI。实际上incrSubCounter和setSubCounter两个函数都不能触发Text('${this.value.subCounter.counter}')的更新,因为\@ObjectLink value : ParentCounter仅能观察其代理ParentCounter的属性,对于this.value.subCounter.counter是SubCounter的属性,无法观察到嵌套类的属性。
1252
1253但是,第一个click事件调用this.counter[0].incrCounter()将CounterComp自定义组件中\@ObjectLink value: ParentCounter标记为已更改。此时触发Text('${this.value.subCounter.counter}')的更新。 如果在第一个点击事件中删除this.counter[0].incrCounter(),也无法更新UI。
1254
1255【正例】
1256
1257对于上述问题,为了直接观察SubCounter中的属性,以便this.counter[0].setSubCounter(10)操作有效,可以利用下面的方法:
1258
1259
1260```ts
1261CounterComp({ value: this.counter[0] }); // ParentComp组件传递 ParentCounter 给 CounterComp 组件
1262@ObjectLink value:ParentCounter; // @ObjectLink 接收 ParentCounter
1263
1264CounterChild({ subValue: this.value.subCounter }); // CounterComp组件 传递 SubCounter 给 CounterChild 组件
1265@ObjectLink subValue:SubCounter; // @ObjectLink 接收 SubCounter
1266```
1267
1268该方法使得\@ObjectLink分别代理了ParentCounter和SubCounter的属性,这样对于这两个类的属性的变化都可以观察到,即都会对UI视图进行刷新。即使删除了上面所说的this.counter[0].incrCounter(),UI也会进行正确的刷新。
1269
1270该方法可用于实现“两个层级”的观察,即外部对象和内部嵌套对象的观察。但是该方法只能用于\@ObjectLink装饰器,无法作用于\@Prop(\@Prop通过深拷贝传入对象)。详情参考[@Prop与@ObjectLink的差异](#prop与objectlink的差异)。
1271
1272
1273```ts
1274let nextId = 1;
1275
1276@Observed
1277class SubCounter {
1278  counter: number;
1279
1280  constructor(c: number) {
1281    this.counter = c;
1282  }
1283}
1284
1285@Observed
1286class ParentCounter {
1287  id: number;
1288  counter: number;
1289  subCounter: SubCounter;
1290
1291  incrCounter() {
1292    this.counter++;
1293  }
1294
1295  incrSubCounter(c: number) {
1296    this.subCounter.counter += c;
1297  }
1298
1299  setSubCounter(c: number): void {
1300    this.subCounter.counter = c;
1301  }
1302
1303  constructor(c: number) {
1304    this.id = nextId++;
1305    this.counter = c;
1306    this.subCounter = new SubCounter(c);
1307  }
1308}
1309
1310@Component
1311struct CounterComp {
1312  @ObjectLink value: ParentCounter;
1313
1314  build() {
1315    Column({ space: 10 }) {
1316      Text(`${this.value.counter}`)
1317        .fontSize(25)
1318        .onClick(() => {
1319          this.value.incrCounter();
1320        })
1321      CounterChild({ subValue: this.value.subCounter })
1322      Divider().height(2)
1323    }
1324  }
1325}
1326
1327@Component
1328struct CounterChild {
1329  @ObjectLink subValue: SubCounter;
1330
1331  build() {
1332    Text(`${this.subValue.counter}`)
1333      .onClick(() => {
1334        this.subValue.counter += 1;
1335      })
1336  }
1337}
1338
1339@Entry
1340@Component
1341struct ParentComp {
1342  @State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1343
1344  build() {
1345    Row() {
1346      Column() {
1347        CounterComp({ value: this.counter[0] })
1348        CounterComp({ value: this.counter[1] })
1349        CounterComp({ value: this.counter[2] })
1350        Divider().height(5)
1351        ForEach(this.counter,
1352          (item: ParentCounter) => {
1353            CounterComp({ value: item })
1354          },
1355          (item: ParentCounter) => item.id.toString()
1356        )
1357        Divider().height(5)
1358        Text('Parent: reset entire counter')
1359          .fontSize(20).height(50)
1360          .onClick(() => {
1361            this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1362          })
1363        Text('Parent: incr counter[0].counter')
1364          .fontSize(20).height(50)
1365          .onClick(() => {
1366            this.counter[0].incrCounter();
1367            this.counter[0].incrSubCounter(10);
1368          })
1369        Text('Parent: set.counter to 10')
1370          .fontSize(20).height(50)
1371          .onClick(() => {
1372            this.counter[0].setSubCounter(10);
1373          })
1374      }
1375    }
1376  }
1377}
1378```
1379
1380### \@Prop与\@ObjectLink的差异
1381
1382在下面的示例代码中,\@ObjectLink装饰的变量是对数据源的引用,即在this.value.subValuethis.subValue都是同一个对象的不同引用,所以在点击CounterComp的click handler,改变this.value.subCounter.counterthis.subValue.counter也会改变,对应的组件Text(`this.subValue.counter: ${this.subValue.counter}`)会刷新。
1383
1384
1385```ts
1386let nextId = 1;
1387
1388@Observed
1389class SubCounter {
1390  counter: number;
1391
1392  constructor(c: number) {
1393    this.counter = c;
1394  }
1395}
1396
1397@Observed
1398class ParentCounter {
1399  id: number;
1400  counter: number;
1401  subCounter: SubCounter;
1402
1403  incrCounter() {
1404    this.counter++;
1405  }
1406
1407  incrSubCounter(c: number) {
1408    this.subCounter.counter += c;
1409  }
1410
1411  setSubCounter(c: number): void {
1412    this.subCounter.counter = c;
1413  }
1414
1415  constructor(c: number) {
1416    this.id = nextId++;
1417    this.counter = c;
1418    this.subCounter = new SubCounter(c);
1419  }
1420}
1421
1422@Component
1423struct CounterComp {
1424  @ObjectLink value: ParentCounter;
1425
1426  build() {
1427    Column({ space: 10 }) {
1428      CountChild({ subValue: this.value.subCounter })
1429      Text(`this.value.counter:increase 7 `)
1430        .fontSize(30)
1431        .onClick(() => {
1432          // click handler, Text(`this.subValue.counter: ${this.subValue.counter}`) will update
1433          this.value.incrSubCounter(7);
1434        })
1435      Divider().height(2)
1436    }
1437  }
1438}
1439
1440@Component
1441struct CountChild {
1442  @ObjectLink subValue: SubCounter;
1443
1444  build() {
1445    Text(`this.subValue.counter: ${this.subValue.counter}`)
1446      .fontSize(30)
1447  }
1448}
1449
1450@Entry
1451@Component
1452struct ParentComp {
1453  @State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1454
1455  build() {
1456    Row() {
1457      Column() {
1458        CounterComp({ value: this.counter[0] })
1459        CounterComp({ value: this.counter[1] })
1460        CounterComp({ value: this.counter[2] })
1461        Divider().height(5)
1462        ForEach(this.counter,
1463          (item: ParentCounter) => {
1464            CounterComp({ value: item })
1465          },
1466          (item: ParentCounter) => item.id.toString()
1467        )
1468        Divider().height(5)
1469        Text('Parent: reset entire counter')
1470          .fontSize(20).height(50)
1471          .onClick(() => {
1472            this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1473          })
1474        Text('Parent: incr counter[0].counter')
1475          .fontSize(20).height(50)
1476          .onClick(() => {
1477            this.counter[0].incrCounter();
1478            this.counter[0].incrSubCounter(10);
1479          })
1480        Text('Parent: set.counter to 10')
1481          .fontSize(20).height(50)
1482          .onClick(() => {
1483            this.counter[0].setSubCounter(10);
1484          })
1485      }
1486    }
1487  }
1488}
1489```
1490
1491\@ObjectLink图示如下:
1492
1493![zh-cn_image_0000001651665921](figures/zh-cn_image_0000001651665921.png)
1494
1495【反例】
1496
1497如果用\@Prop替代\@ObjectLink。点击第一个click handler,UI刷新正常。但是点击第二个onClick事件,\@Prop 对变量做了一个本地拷贝,CounterComp的第一个Text并不会刷新。
1498
1499  this.value.subCounterthis.subValue并不是同一个对象。所以this.value.subCounter的改变,并没有改变this.subValue的拷贝对象,Text(`this.subValue.counter: ${this.subValue.counter}`)不会刷新。
1500
1501```ts
1502@Component
1503struct CounterComp {
1504  @Prop value: ParentCounter = new ParentCounter(0);
1505  @Prop subValue: SubCounter = new SubCounter(0);
1506  build() {
1507    Column({ space: 10 }) {
1508      Text(`this.subValue.counter: ${this.subValue.counter}`)
1509        .fontSize(20)
1510        .onClick(() => {
1511          // 1st click handler
1512          this.subValue.counter += 7;
1513        })
1514      Text(`this.value.counter:increase 7 `)
1515        .fontSize(20)
1516        .onClick(() => {
1517          // 2nd click handler
1518          this.value.incrSubCounter(7);
1519        })
1520      Divider().height(2)
1521    }
1522  }
1523}
1524```
1525
1526\@Prop拷贝的关系图示如下:
1527
1528![zh-cn_image_0000001602146116](figures/zh-cn_image_0000001602146116.png)
1529
1530【正例】
1531
1532可以通过从ParentComp到CounterComp仅拷贝一份\@Prop value: ParentCounter,同时必须避免再多拷贝一份SubCounter。
1533
1534- 在CounterComp组件中只使用一个\@Prop counter:Counter。
1535
1536- 添加另一个子组件SubCounterComp,其中包含\@ObjectLink subCounter: SubCounter。此\@ObjectLink可确保观察到SubCounter对象属性更改,并且UI更新正常。
1537
1538- \@ObjectLink subCounter: SubCounter与CounterComp中的\@Prop counter:Counter的this.counter.subCounter共享相同的SubCounter对象。
1539
1540  
1541
1542```ts
1543let nextId = 1;
1544
1545@Observed
1546class SubCounter {
1547  counter: number;
1548  constructor(c: number) {
1549    this.counter = c;
1550  }
1551}
1552
1553@Observed
1554class ParentCounter {
1555  id: number;
1556  counter: number;
1557  subCounter: SubCounter;
1558  incrCounter() {
1559    this.counter++;
1560  }
1561  incrSubCounter(c: number) {
1562    this.subCounter.counter += c;
1563  }
1564  setSubCounter(c: number): void {
1565    this.subCounter.counter = c;
1566  }
1567  constructor(c: number) {
1568    this.id = nextId++;
1569    this.counter = c;
1570    this.subCounter = new SubCounter(c);
1571  }
1572}
1573
1574@Component
1575struct SubCounterComp {
1576  @ObjectLink subValue: SubCounter;
1577  build() {
1578    Text(`SubCounterComp: this.subValue.counter: ${this.subValue.counter}`)
1579      .onClick(() => {
1580        // 2nd click handler
1581        this.subValue.counter = 7;
1582      })
1583  }
1584}
1585@Component
1586struct CounterComp {
1587  @Prop value: ParentCounter;
1588  build() {
1589    Column({ space: 10 }) {
1590      Text(`this.value.incrCounter(): this.value.counter: ${this.value.counter}`)
1591        .fontSize(20)
1592        .onClick(() => {
1593          // 1st click handler
1594          this.value.incrCounter();
1595        })
1596      SubCounterComp({ subValue: this.value.subCounter })
1597      Text(`this.value.incrSubCounter()`)
1598        .onClick(() => {
1599          // 3rd click handler
1600          this.value.incrSubCounter(77);
1601        })
1602      Divider().height(2)
1603    }
1604  }
1605}
1606@Entry
1607@Component
1608struct ParentComp {
1609  @State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1610  build() {
1611    Row() {
1612      Column() {
1613        CounterComp({ value: this.counter[0] })
1614        CounterComp({ value: this.counter[1] })
1615        CounterComp({ value: this.counter[2] })
1616        Divider().height(5)
1617        ForEach(this.counter,
1618          (item: ParentCounter) => {
1619            CounterComp({ value: item })
1620          },
1621          (item: ParentCounter) => item.id.toString()
1622        )
1623        Divider().height(5)
1624        Text('Parent: reset entire counter')
1625          .fontSize(20).height(50)
1626          .onClick(() => {
1627            this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
1628          })
1629        Text('Parent: incr counter[0].counter')
1630          .fontSize(20).height(50)
1631          .onClick(() => {
1632            this.counter[0].incrCounter();
1633            this.counter[0].incrSubCounter(10);
1634          })
1635        Text('Parent: set.counter to 10')
1636          .fontSize(20).height(50)
1637          .onClick(() => {
1638            this.counter[0].setSubCounter(10);
1639          })
1640      }
1641    }
1642  }
1643}
1644```
1645
1646
1647拷贝关系图示如下:
1648
1649
1650![zh-cn_image_0000001653949465](figures/zh-cn_image_0000001653949465.png)
1651
1652### 在@Observed装饰类的构造函数中延时更改成员变量
1653
1654在状态管理中,使用@Observed装饰类后,会给该类使用一层“代理”进行包装。当在组件中改变该类的成员变量时,会被该代理进行拦截,在更改数据源中值的同时,也会将变化通知给绑定的组件,从而实现观测变化与触发刷新。
1655
1656当开发者在类的构造函数中对成员变量进行赋值或者修改时,此修改不会经过代理(因为是直接对数据源中的值进行修改),也就无法被观测到。所以,如果开发者在类的构造函数中使用定时器修改类中的成员变量,即使该修改成功执行了,也不会触发UI的刷新。
1657
1658【反例】
1659
1660```ts
1661@Observed
1662class RenderClass {
1663  waitToRender: boolean = false;
1664
1665  constructor() {
1666    setTimeout(() => {
1667      this.waitToRender = true;
1668      console.log("更改waitToRender的值为:" + this.waitToRender);
1669    }, 1000)
1670  }
1671}
1672
1673@Entry
1674@Component
1675struct Index {
1676  @State @Watch('renderClassChange') renderClass: RenderClass = new RenderClass();
1677  @State textColor: Color = Color.Black;
1678
1679  renderClassChange() {
1680    console.log("renderClass的值被更改为:" + this.renderClass.waitToRender);
1681  }
1682
1683  build() {
1684    Row() {
1685      Column() {
1686        Text("renderClass的值为:" + this.renderClass.waitToRender)
1687          .fontSize(20)
1688          .fontColor(this.textColor)
1689        Button("Show")
1690          .onClick(() => {
1691            // 使用其他状态变量强行刷新UI的做法并不推荐,此处仅用来检测waitToRender的值是否更新
1692            this.textColor = Color.Red;
1693          })
1694      }
1695      .width('100%')
1696    }
1697    .height('100%')
1698  }
1699}
1700```
1701
1702上文的示例代码中在RenderClass的构造函数中使用定时器在1秒后修改了waitToRender的值,但是不会触发UI的刷新。此时点击按钮,强行刷新Text组件可以看到waitToRender的值已经被修改成了true。
1703
1704【正例】
1705
1706```ts
1707@Observed
1708class RenderClass {
1709  waitToRender: boolean = false;
1710
1711  constructor() {
1712  }
1713}
1714
1715@Entry
1716@Component
1717struct Index {
1718  @State @Watch('renderClassChange') renderClass: RenderClass = new RenderClass();
1719
1720  renderClassChange() {
1721    console.log("renderClass的值被更改为:" + this.renderClass.waitToRender);
1722  }
1723
1724  onPageShow() {
1725    setTimeout(() => {
1726      this.renderClass.waitToRender = true;
1727      console.log("更改renderClass的值为:" + this.renderClass.waitToRender);
1728    }, 1000)
1729  }
1730
1731  build() {
1732    Row() {
1733      Column() {
1734        Text("renderClass的值为:" + this.renderClass.waitToRender)
1735          .fontSize(20)
1736      }
1737      .width('100%')
1738    }
1739    .height('100%')
1740  }
1741}
1742```
1743
1744上文的示例代码将定时器修改移入到组件内,此时界面显示时会先显示“renderClass的值为:false”。待定时器触发时,renderClass的值改变,触发[@Watch](./arkts-watch.md)回调,此时界面刷新显示“renderClass的值为:true”,日志输出“renderClass的值被更改为:true”。
1745
1746因此,更推荐开发者在组件中对@Observed装饰的类成员变量进行修改实现刷新。
1747
1748### ObjectLink更新依赖其所属自定义组件的更新函数
1749
1750```ts
1751@Observed
1752class Person {
1753  name: string = '';
1754  age: number = 0;
1755
1756  constructor(name: string, age: number) {
1757    this.name = name;
1758    this.age = age;
1759  }
1760}
1761
1762@Observed
1763class Persons {
1764  person: Person;
1765
1766  constructor(person: Person) {
1767    this.person = person;
1768  }
1769}
1770
1771@Entry
1772@Component
1773struct Parent {
1774  @State pers01: Persons = new Persons(new Person('1', 1));
1775
1776  build() {
1777    Column() {
1778      Child01({ pers: this.pers01 });
1779    }
1780  }
1781}
1782
1783@Component
1784struct Child01 {
1785  @ObjectLink @Watch('onChange01') pers: Persons;
1786
1787  onChange01() {
1788    console.log(':::onChange01:' + this.pers.person.name); // 2
1789  }
1790
1791  build() {
1792    Column() {
1793      Text(this.pers.person.name).height(40)
1794      Child02({
1795        per: this.pers.person, selectItemBlock: () => {
1796          console.log(':::selectItemBlock before', this.pers.person.name); // 1
1797          this.pers.person = new Person('2', 2);
1798          console.log(':::selectItemBlock after', this.pers.person.name); // 3
1799        }
1800      })
1801    }
1802  }
1803}
1804
1805@Component
1806struct Child02 {
1807  @ObjectLink @Watch('onChange02') per: Person;
1808  selectItemBlock?: () => void;
1809
1810  onChange02() {
1811    console.log(':::onChange02:' + this.per.name); // 5
1812  }
1813
1814  build() {
1815    Column() {
1816      Button(this.per.name)
1817        .height(40)
1818        .onClick(() => {
1819          this.onClickFType();
1820        })
1821    }
1822  }
1823
1824  private onClickFType() {
1825    if (this.selectItemBlock) {
1826      this.selectItemBlock();
1827    }
1828    console.log(':::--------此时Child02中的this.per.name值仍然是:' + this.per.name); // 4
1829  }
1830}
1831```
1832
1833数据源通知@ObjectLink是依赖@ObjectLink所属自定义组件更新,是异步调用。上述示例中,Parent包含Child01,Child01包含Child02,在进行点击时,Child01传箭头函数给Child02,此时调用Child02的点击事件,日志打印顺序是1-2-3-4-5,打印到日志4时,点击事件流程结束,此时仅仅是给子组件Child02标脏,Child02的更新要等待下一次vsync信号,而@ObjectLink的更新依赖其所属自定义组件的更新函数,所以日志4打印的this.per.name的值仍然是1。
1834
1835当@ObjectLink @Watch('onChange02') per: Person的@Watch函数执行时,当前已执行Child02的更新函数,@ObjectLink已被通知更新,所以日志5打印的值为2。
1836
1837日志的含义为:
1838- 日志1:对Child01 @ObjectLink @Watch('onChange01') pers: Persons 赋值前。
1839
1840- 日志2:对Child01 @ObjectLink @Watch('onChange01') pers: Persons 赋值,执行其@Watch函数,同步执行。
1841
1842- 日志3:对Child01 @ObjectLink @Watch('onChange01') pers: Persons 赋值完成。
1843
1844- 日志4:onClickFType方法内selectItemBlock执行完,此时只做了标脏,未将最新的值更新给Child02 @ObjectLink @Watch('onChange02') per: Person,所以日志4打印的this.per.name的值仍然是1。
1845
1846- 日志5:下一次vsync信号触发Child02更新,@ObjectLink @Watch('onChange02') per: Person被更新,触发其@Watch方法,此时@ObjectLink @Watch('onChange02') per: Person为新值2。
1847
1848@Prop父子同步原理同@ObjectLink一致。
1849
1850当selectItemBlock中更改this.pers.person.name时,修改会立刻生效,此时日志4打印的值是2。
1851
1852```ts
1853Child02({
1854  per: this.pers.person, selectItemBlock: () => {
1855    console.log(':::selectItemBlock before', this.pers.person.name); // 1
1856    this.pers.person.name = 2;
1857    console.log(':::selectItemBlock after', this.pers.person.name); // 3
1858  }
1859})
1860```
1861
1862此时Child01中Text组件不会刷新,因为this.pers.person.name属于两层嵌套。
1863
1864### 使用a.b(this.object)形式调用,不会触发UI刷新
1865
1866在build方法内,当@Observed与@ObjectLink联合装饰的变量是Object类型、且通过a.b(this.object)形式调用时,b方法内传入的是this.object的原生对象,修改其属性,无法触发UI刷新。如下例中,通过静态方法或者使用this调用组件内部方法,修改组件中的this.weather.temperature时,UI不会刷新。
1867
1868【反例】
1869
1870```ts
1871@Observed
1872class Weather {
1873  temperature:number;
1874
1875  constructor(temperature:number) {
1876    this.temperature = temperature;
1877  }
1878
1879  static increaseTemperature(weather:Weather) {
1880    weather.temperature++;
1881  }
1882}
1883
1884class Day {
1885  weather:Weather;
1886  week:string;
1887  constructor(weather:Weather, week:string) {
1888    this.weather = weather;
1889    this.week = week;
1890  }
1891}
1892
1893@Entry
1894@Component
1895struct Parent {
1896  @State day1: Day = new Day(new Weather(15), 'Monday');
1897
1898  build() {
1899    Column({ space:10 }) {
1900      Child({ weather: this.day1.weather})
1901    }
1902    .height('100%')
1903    .width('100%')
1904  }
1905}
1906
1907@Component
1908struct Child {
1909  @ObjectLink weather: Weather;
1910
1911  reduceTemperature (weather:Weather) {
1912    weather.temperature--;
1913  }
1914
1915  build() {
1916    Column({ space:10 }) {
1917      Text(`The temperature of day1 is ${this.weather.temperature} degrees.`)
1918        .fontSize(20)
1919      Button('increaseTemperature')
1920        .onClick(()=>{
1921          // 通过静态方法调用,无法触发UI刷新
1922          Weather.increaseTemperature(this.weather);
1923        })
1924      Button('reduceTemperature')
1925        .onClick(()=>{
1926          // 使用this通过自定义组件内部方法调用,无法触发UI刷新
1927          this.reduceTemperature(this.weather);
1928        })
1929    }
1930    .height('100%')
1931    .width('100%')
1932  }
1933}
1934```
1935
1936可以通过如下先赋值、再调用新赋值的变量的方式为this.weather加上Proxy代理,实现UI刷新。
1937
1938【正例】
1939
1940```ts
1941@Observed
1942class Weather {
1943  temperature:number;
1944
1945  constructor(temperature:number) {
1946    this.temperature = temperature;
1947  }
1948
1949  static increaseTemperature(weather:Weather) {
1950    weather.temperature++;
1951  }
1952}
1953
1954class Day {
1955  weather:Weather;
1956  week:string;
1957  constructor(weather:Weather, week:string) {
1958    this.weather = weather;
1959    this.week = week;
1960  }
1961}
1962
1963@Entry
1964@Component
1965struct Parent {
1966  @State day1: Day = new Day(new Weather(15), 'Monday');
1967
1968  build() {
1969    Column({ space:10 }) {
1970      Child({ weather: this.day1.weather})
1971    }
1972    .height('100%')
1973    .width('100%')
1974  }
1975}
1976
1977@Component
1978struct Child {
1979  @ObjectLink weather: Weather;
1980
1981  reduceTemperature (weather:Weather) {
1982    weather.temperature--;
1983  }
1984
1985  build() {
1986    Column({ space:10 }) {
1987      Text(`The temperature of day1 is ${this.weather.temperature} degrees.`)
1988        .fontSize(20)
1989      Button('increaseTemperature')
1990        .onClick(()=>{
1991          // 通过赋值添加 Proxy 代理
1992          let weather1 = this.weather;
1993          Weather.increaseTemperature(weather1);
1994        })
1995      Button('reduceTemperature')
1996        .onClick(()=>{
1997          // 通过赋值添加 Proxy 代理
1998          let weather2 = this.weather;
1999          this.reduceTemperature(weather2);
2000        })
2001    }
2002    .height('100%')
2003    .width('100%')
2004  }
2005}
2006```
2007