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