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/>- 类型必须是\@Observed装饰的class。<br/>- 初始化的数值需要是数组项,或者class的属性。<br/>- 同步源的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 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 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 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 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 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 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 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 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.cousinId 和this.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 1396// CounterChild 是 CounterComp 的子组件,CounterComp 传递 this.value.subCounter 给 CounterChild 组件 1397CounterChild({ subValue: this.value.subCounter }); 1398@ObjectLink subValue:SubCounter; // @ObjectLink 接收 SubCounter 1399``` 1400 1401该方法使得\@ObjectLink分别代理了ParentCounter和SubCounter的属性,这样对于这两个类的属性的变化都可以观察到,即都会对UI视图进行刷新。即使删除了上面所说的this.counter[0].incrCounter(),UI也会进行正确的刷新。 1402 1403该方法可用于实现“两个层级”的观察,即外部对象和内部嵌套对象的观察。但是该方法只能用于\@ObjectLink装饰器,无法作用于\@Prop(\@Prop通过深拷贝传入对象)。详情参考[@Prop与@ObjectLink的差异](#prop与objectlink的差异)。 1404 1405 1406```ts 1407let nextId = 1; 1408 1409@Observed 1410class SubCounter { 1411 counter: number; 1412 1413 constructor(c: number) { 1414 this.counter = c; 1415 } 1416} 1417 1418@Observed 1419class ParentCounter { 1420 id: number; 1421 counter: number; 1422 subCounter: SubCounter; 1423 1424 incrCounter() { 1425 this.counter++; 1426 } 1427 1428 incrSubCounter(c: number) { 1429 this.subCounter.counter += c; 1430 } 1431 1432 setSubCounter(c: number): void { 1433 this.subCounter.counter = c; 1434 } 1435 1436 constructor(c: number) { 1437 this.id = nextId++; 1438 this.counter = c; 1439 this.subCounter = new SubCounter(c); 1440 } 1441} 1442 1443@Component 1444struct CounterComp { 1445 @ObjectLink value: ParentCounter; 1446 1447 build() { 1448 Column({ space: 10 }) { 1449 Text(`${this.value.counter}`) 1450 .fontSize(25) 1451 .onClick(() => { 1452 this.value.incrCounter(); 1453 }) 1454 CounterChild({ subValue: this.value.subCounter }) 1455 Divider().height(2) 1456 } 1457 } 1458} 1459 1460@Component 1461struct CounterChild { 1462 @ObjectLink subValue: SubCounter; 1463 1464 build() { 1465 Text(`${this.subValue.counter}`) 1466 .onClick(() => { 1467 this.subValue.counter += 1; 1468 }) 1469 } 1470} 1471 1472@Entry 1473@Component 1474struct ParentComp { 1475 @State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)]; 1476 1477 build() { 1478 Row() { 1479 Column() { 1480 CounterComp({ value: this.counter[0] }) 1481 CounterComp({ value: this.counter[1] }) 1482 CounterComp({ value: this.counter[2] }) 1483 Divider().height(5) 1484 ForEach(this.counter, 1485 (item: ParentCounter) => { 1486 CounterComp({ value: item }) 1487 }, 1488 (item: ParentCounter) => item.id.toString() 1489 ) 1490 Divider().height(5) 1491 Text('Parent: reset entire counter') 1492 .fontSize(20).height(50) 1493 .onClick(() => { 1494 this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)]; 1495 }) 1496 Text('Parent: incr counter[0].counter') 1497 .fontSize(20).height(50) 1498 .onClick(() => { 1499 this.counter[0].incrCounter(); 1500 this.counter[0].incrSubCounter(10); 1501 }) 1502 Text('Parent: set.counter to 10') 1503 .fontSize(20).height(50) 1504 .onClick(() => { 1505 this.counter[0].setSubCounter(10); 1506 }) 1507 } 1508 } 1509 } 1510} 1511``` 1512 1513### \@Prop与\@ObjectLink的差异 1514 1515在下面的示例代码中,\@ObjectLink装饰的变量是对数据源的引用,即this.value.subCounter和this.subValue都是同一个对象的不同引用,所以在点击CounterComp的click handler,改变this.value.subCounter.counter时,this.subValue.counter也会改变,对应的组件Text(`this.subValue.counter: ${this.subValue.counter}`)会刷新。 1516 1517 1518```ts 1519let nextId = 1; 1520 1521@Observed 1522class SubCounter { 1523 counter: number; 1524 1525 constructor(c: number) { 1526 this.counter = c; 1527 } 1528} 1529 1530@Observed 1531class ParentCounter { 1532 id: number; 1533 counter: number; 1534 subCounter: SubCounter; 1535 1536 incrCounter() { 1537 this.counter++; 1538 } 1539 1540 incrSubCounter(c: number) { 1541 this.subCounter.counter += c; 1542 } 1543 1544 setSubCounter(c: number): void { 1545 this.subCounter.counter = c; 1546 } 1547 1548 constructor(c: number) { 1549 this.id = nextId++; 1550 this.counter = c; 1551 this.subCounter = new SubCounter(c); 1552 } 1553} 1554 1555@Component 1556struct CounterComp { 1557 @ObjectLink value: ParentCounter; 1558 1559 build() { 1560 Column({ space: 10 }) { 1561 CountChild({ subValue: this.value.subCounter }) 1562 Text(`this.value.counter:increase 7 `) 1563 .fontSize(30) 1564 .onClick(() => { 1565 // 点击后Text(`this.subValue.counter: ${this.subValue.counter}`)会刷新 1566 this.value.incrSubCounter(7); 1567 }) 1568 Divider().height(2) 1569 } 1570 } 1571} 1572 1573@Component 1574struct CountChild { 1575 @ObjectLink subValue: SubCounter; 1576 1577 build() { 1578 Text(`this.subValue.counter: ${this.subValue.counter}`) 1579 .fontSize(30) 1580 } 1581} 1582 1583@Entry 1584@Component 1585struct ParentComp { 1586 @State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)]; 1587 1588 build() { 1589 Row() { 1590 Column() { 1591 CounterComp({ value: this.counter[0] }) 1592 CounterComp({ value: this.counter[1] }) 1593 CounterComp({ value: this.counter[2] }) 1594 Divider().height(5) 1595 ForEach(this.counter, 1596 (item: ParentCounter) => { 1597 CounterComp({ value: item }) 1598 }, 1599 (item: ParentCounter) => item.id.toString() 1600 ) 1601 Divider().height(5) 1602 Text('Parent: reset entire counter') 1603 .fontSize(20).height(50) 1604 .onClick(() => { 1605 this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)]; 1606 }) 1607 Text('Parent: incr counter[0].counter') 1608 .fontSize(20).height(50) 1609 .onClick(() => { 1610 this.counter[0].incrCounter(); 1611 this.counter[0].incrSubCounter(10); 1612 }) 1613 Text('Parent: set.counter to 10') 1614 .fontSize(20).height(50) 1615 .onClick(() => { 1616 this.counter[0].setSubCounter(10); 1617 }) 1618 } 1619 } 1620 } 1621} 1622``` 1623 1624\@ObjectLink图示如下: 1625 1626 1627 1628【反例】 1629 1630如果用\@Prop替代\@ObjectLink。点击Text(`this.subValue.counter: ${this.subValue.counter}`),UI刷新正常。但是点击Text(`this.value.counter:increase 7 `),\@Prop 对变量做了一个本地拷贝,CounterComp的第一个Text并不会刷新。 1631 1632 this.value.subCounter和this.subValue并不是同一个对象。所以this.value.subCounter的改变,并没有改变this.subValue的拷贝对象,Text(`this.subValue.counter: ${this.subValue.counter}`)不会刷新。 1633 1634```ts 1635@Component 1636struct CounterComp { 1637 @Prop value: ParentCounter = new ParentCounter(0); 1638 @Prop subValue: SubCounter = new SubCounter(0); 1639 build() { 1640 Column({ space: 10 }) { 1641 Text(`this.subValue.counter: ${this.subValue.counter}`) 1642 .fontSize(20) 1643 .onClick(() => { 1644 this.subValue.counter += 7; 1645 }) 1646 Text(`this.value.counter:increase 7 `) 1647 .fontSize(20) 1648 .onClick(() => { 1649 this.value.incrSubCounter(7); 1650 }) 1651 Divider().height(2) 1652 } 1653 } 1654} 1655``` 1656 1657\@Prop拷贝的关系图示如下: 1658 1659 1660 1661【正例】 1662 1663可以通过从ParentComp到CounterComp仅拷贝一份\@Prop value: ParentCounter,同时必须避免再多拷贝一份SubCounter。 1664 1665- 在CounterComp组件中只使用一个\@Prop counter:Counter。 1666 1667- 添加另一个子组件SubCounterComp,其中包含\@ObjectLink subCounter: SubCounter。此\@ObjectLink可确保观察到SubCounter对象属性更改,并且UI更新正常。 1668 1669- \@ObjectLink subCounter: SubCounter与CounterComp中的\@Prop counter:Counter的this.counter.subCounter共享相同的SubCounter对象。 1670 1671 1672 1673```ts 1674let nextId = 1; 1675 1676@Observed 1677class SubCounter { 1678 counter: number; 1679 constructor(c: number) { 1680 this.counter = c; 1681 } 1682} 1683 1684@Observed 1685class ParentCounter { 1686 id: number; 1687 counter: number; 1688 subCounter: SubCounter; 1689 incrCounter() { 1690 this.counter++; 1691 } 1692 incrSubCounter(c: number) { 1693 this.subCounter.counter += c; 1694 } 1695 setSubCounter(c: number): void { 1696 this.subCounter.counter = c; 1697 } 1698 constructor(c: number) { 1699 this.id = nextId++; 1700 this.counter = c; 1701 this.subCounter = new SubCounter(c); 1702 } 1703} 1704 1705@Component 1706struct SubCounterComp { 1707 @ObjectLink subValue: SubCounter; 1708 build() { 1709 Text(`SubCounterComp: this.subValue.counter: ${this.subValue.counter}`) 1710 .onClick(() => { 1711 this.subValue.counter = 7; 1712 }) 1713 } 1714} 1715@Component 1716struct CounterComp { 1717 @Prop value: ParentCounter; 1718 build() { 1719 Column({ space: 10 }) { 1720 Text(`this.value.incrCounter(): this.value.counter: ${this.value.counter}`) 1721 .fontSize(20) 1722 .onClick(() => { 1723 this.value.incrCounter(); 1724 }) 1725 SubCounterComp({ subValue: this.value.subCounter }) 1726 Text(`this.value.incrSubCounter()`) 1727 .onClick(() => { 1728 this.value.incrSubCounter(77); 1729 }) 1730 Divider().height(2) 1731 } 1732 } 1733} 1734@Entry 1735@Component 1736struct ParentComp { 1737 @State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)]; 1738 build() { 1739 Row() { 1740 Column() { 1741 CounterComp({ value: this.counter[0] }) 1742 CounterComp({ value: this.counter[1] }) 1743 CounterComp({ value: this.counter[2] }) 1744 Divider().height(5) 1745 ForEach(this.counter, 1746 (item: ParentCounter) => { 1747 CounterComp({ value: item }) 1748 }, 1749 (item: ParentCounter) => item.id.toString() 1750 ) 1751 Divider().height(5) 1752 Text('Parent: reset entire counter') 1753 .fontSize(20).height(50) 1754 .onClick(() => { 1755 this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)]; 1756 }) 1757 Text('Parent: incr counter[0].counter') 1758 .fontSize(20).height(50) 1759 .onClick(() => { 1760 this.counter[0].incrCounter(); 1761 this.counter[0].incrSubCounter(10); 1762 }) 1763 Text('Parent: set.counter to 10') 1764 .fontSize(20).height(50) 1765 .onClick(() => { 1766 this.counter[0].setSubCounter(10); 1767 }) 1768 } 1769 } 1770 } 1771} 1772``` 1773 1774 1775拷贝关系图示如下: 1776 1777 1778 1779 1780### 在@Observed装饰类的构造函数中延时更改成员变量 1781 1782在状态管理中,使用@Observed装饰类后,会给该类使用一层“代理”进行包装。当在组件中改变该类的成员变量时,会被该代理进行拦截,在更改数据源中值的同时,也会将变化通知给绑定的组件,从而实现观测变化与触发刷新。 1783 1784当开发者在类的构造函数中对成员变量进行赋值或者修改时,此修改不会经过代理(因为是直接对数据源中的值进行修改),也就无法被观测到。所以,如果开发者在类的构造函数中使用定时器修改类中的成员变量,即使该修改成功执行了,也不会触发UI的刷新。 1785 1786【反例】 1787 1788```ts 1789@Observed 1790class RenderClass { 1791 waitToRender: boolean = false; 1792 1793 constructor() { 1794 setTimeout(() => { 1795 this.waitToRender = true; 1796 console.log("更改waitToRender的值为:" + this.waitToRender); 1797 }, 1000) 1798 } 1799} 1800 1801@Entry 1802@Component 1803struct Index { 1804 @State @Watch('renderClassChange') renderClass: RenderClass = new RenderClass(); 1805 @State textColor: Color = Color.Black; 1806 1807 renderClassChange() { 1808 console.log("renderClass的值被更改为:" + this.renderClass.waitToRender); 1809 } 1810 1811 build() { 1812 Row() { 1813 Column() { 1814 Text("renderClass的值为:" + this.renderClass.waitToRender) 1815 .fontSize(20) 1816 .fontColor(this.textColor) 1817 Button("Show") 1818 .onClick(() => { 1819 // 使用其他状态变量强行刷新UI的做法并不推荐,此处仅用来检测waitToRender的值是否更新 1820 this.textColor = Color.Red; 1821 }) 1822 } 1823 .width('100%') 1824 } 1825 .height('100%') 1826 } 1827} 1828``` 1829 1830上文的示例代码中在RenderClass的构造函数中使用定时器在1秒后修改了waitToRender的值,但是不会触发UI的刷新。此时点击按钮,强行刷新Text组件可以看到waitToRender的值已经被修改成了true。 1831 1832【正例】 1833 1834```ts 1835@Observed 1836class RenderClass { 1837 waitToRender: boolean = false; 1838 1839 constructor() { 1840 } 1841} 1842 1843@Entry 1844@Component 1845struct Index { 1846 @State @Watch('renderClassChange') renderClass: RenderClass = new RenderClass(); 1847 1848 renderClassChange() { 1849 console.log("renderClass的值被更改为:" + this.renderClass.waitToRender); 1850 } 1851 1852 onPageShow() { 1853 setTimeout(() => { 1854 this.renderClass.waitToRender = true; 1855 console.log("更改renderClass的值为:" + this.renderClass.waitToRender); 1856 }, 1000) 1857 } 1858 1859 build() { 1860 Row() { 1861 Column() { 1862 Text("renderClass的值为:" + this.renderClass.waitToRender) 1863 .fontSize(20) 1864 } 1865 .width('100%') 1866 } 1867 .height('100%') 1868 } 1869} 1870``` 1871 1872上文的示例代码将定时器修改移入到组件内,此时界面显示时会先显示“renderClass的值为:false”。待定时器触发时,renderClass的值改变,触发[@Watch](./arkts-watch.md)回调,此时界面刷新显示“renderClass的值为:true”,日志输出“renderClass的值被更改为:true”。 1873 1874因此,更推荐开发者在组件中对@Observed装饰的类成员变量进行修改实现刷新。 1875 1876### \@ObjectLink数据源更新时机 1877 1878```ts 1879@Observed 1880class Person { 1881 name: string = ''; 1882 age: number = 0; 1883 1884 constructor(name: string, age: number) { 1885 this.name = name; 1886 this.age = age; 1887 } 1888} 1889 1890@Observed 1891class Info { 1892 person: Person; 1893 1894 constructor(person: Person) { 1895 this.person = person; 1896 } 1897} 1898 1899@Entry 1900@Component 1901struct Parent { 1902 @State @Watch('onChange01') info: Info = new Info(new Person('Bob', 10)); 1903 1904 onChange01() { 1905 console.log(':::onChange01:' + this.info.person.name); // 2 1906 } 1907 1908 build() { 1909 Column() { 1910 Text(this.info.person.name).height(40) 1911 Child({ 1912 per: this.info.person, clickEvent: () => { 1913 console.log(':::clickEvent before', this.info.person.name); // 1 1914 this.info.person = new Person('Jack', 12); 1915 console.log(':::clickEvent after', this.info.person.name); // 3 1916 } 1917 }) 1918 } 1919 } 1920} 1921 1922@Component 1923struct Child { 1924 @ObjectLink @Watch('onChange02') per: Person; 1925 clickEvent?: () => void; 1926 1927 onChange02() { 1928 console.log(':::onChange02:' + this.per.name); // 5 1929 } 1930 1931 build() { 1932 Column() { 1933 Button(this.per.name) 1934 .height(40) 1935 .onClick(() => { 1936 this.onClickType(); 1937 }) 1938 } 1939 } 1940 1941 private onClickType() { 1942 if (this.clickEvent) { 1943 this.clickEvent(); 1944 } 1945 console.log(':::--------此时Child中的this.per.name值仍然是:' + this.per.name); // 4 1946 } 1947} 1948``` 1949 1950\@ObjectLink的数据源更新依赖其父组件,当父组件中数据源改变引起父组件刷新时,会重新设置子组件\@ObjectLink的数据源。这个过程不是在父组件数据源变化后立刻发生的,而是在父组件实际刷新时才会进行。上述示例中,Parent包含Child,Parent传递箭头函数给Child,在点击时,日志打印顺序是1-2-3-4-5,打印到日志4时,点击事件流程结束,此时仅仅是将子组件Child标记为需要父组件更新的节点,因此日志4打印的this.per.name的值仍为Bob,等到父组件真正更新时,才会更新Child的数据源。 1951 1952当@ObjectLink @Watch('onChange02') per: Person的\@Watch函数执行时,说明\@ObjectLink的数据源已被父组件更新,此时日志5打印的值为更新后的Jack。 1953 1954日志的含义为: 1955- 日志1:对Parent @State @Watch('onChange01') info: Info = new Info(new Person('Bob', 10)) 赋值前。 1956 1957- 日志2:对Parent @State @Watch('onChange01') info: Info = new Info(new Person('Bob', 10)) 赋值,执行其\@Watch函数,同步执行。 1958 1959- 日志3:对Parent @State @Watch('onChange01') info: Info = new Info(new Person('Bob', 10)) 赋值完成。 1960 1961- 日志4:onClickType方法内clickEvent执行完,此时只是将子组件Child标记为需要父组件更新的节点,未将最新的值更新给Child @ObjectLink @Watch('onChange02') per: Person,所以日志4打印的this.per.name的值仍然是Bob。 1962 1963- 日志5:下一次vsync信号触发Child更新,@ObjectLink @Watch('onChange02') per: Person被更新,触发其\@Watch方法,此时@ObjectLink @Watch('onChange02') per: Person为新值Jack。 1964 1965\@Prop父子同步原理同\@ObjectLink一致。 1966 1967当clickEvent中更改this.info.person.name时,修改会立刻生效,此时日志4打印的值是Jack。 1968 1969```ts 1970Child({ 1971 per: this.info.person, clickEvent: () => { 1972 console.log(':::clickEvent before', this.info.person.name); // 1 1973 this.info.person.name = 'Jack'; 1974 console.log(':::clickEvent after', this.info.person.name); // 3 1975 } 1976}) 1977``` 1978 1979此时Parent中Text组件不会刷新,因为this.info.person.name属于两层嵌套。 1980 1981### 使用a.b(this.object)形式调用,不会触发UI刷新 1982 1983在build方法内,当@Observed与@ObjectLink联合装饰的变量是Object类型、且通过a.b(this.object)形式调用时,b方法内传入的是this.object的原始对象,修改其属性,无法触发UI刷新。如下例中,通过静态方法或者使用this调用组件内部方法,修改组件中的this.weather.temperature时,UI不会刷新。 1984 1985【反例】 1986 1987```ts 1988@Observed 1989class Weather { 1990 temperature:number; 1991 1992 constructor(temperature:number) { 1993 this.temperature = temperature; 1994 } 1995 1996 static increaseTemperature(weather:Weather) { 1997 weather.temperature++; 1998 } 1999} 2000 2001class Day { 2002 weather:Weather; 2003 week:string; 2004 constructor(weather:Weather, week:string) { 2005 this.weather = weather; 2006 this.week = week; 2007 } 2008} 2009 2010@Entry 2011@Component 2012struct Parent { 2013 @State day1: Day = new Day(new Weather(15), 'Monday'); 2014 2015 build() { 2016 Column({ space:10 }) { 2017 Child({ weather: this.day1.weather}) 2018 } 2019 .height('100%') 2020 .width('100%') 2021 } 2022} 2023 2024@Component 2025struct Child { 2026 @ObjectLink weather: Weather; 2027 2028 reduceTemperature (weather:Weather) { 2029 weather.temperature--; 2030 } 2031 2032 build() { 2033 Column({ space:10 }) { 2034 Text(`The temperature of day1 is ${this.weather.temperature} degrees.`) 2035 .fontSize(20) 2036 Button('increaseTemperature') 2037 .onClick(()=>{ 2038 // 通过静态方法调用,无法触发UI刷新 2039 Weather.increaseTemperature(this.weather); 2040 }) 2041 Button('reduceTemperature') 2042 .onClick(()=>{ 2043 // 使用this通过自定义组件内部方法调用,无法触发UI刷新 2044 this.reduceTemperature(this.weather); 2045 }) 2046 } 2047 .height('100%') 2048 .width('100%') 2049 } 2050} 2051``` 2052 2053可以通过如下先赋值、再调用新赋值的变量的方式为this.weather加上Proxy代理,实现UI刷新。 2054 2055【正例】 2056 2057```ts 2058@Observed 2059class Weather { 2060 temperature:number; 2061 2062 constructor(temperature:number) { 2063 this.temperature = temperature; 2064 } 2065 2066 static increaseTemperature(weather:Weather) { 2067 weather.temperature++; 2068 } 2069} 2070 2071class Day { 2072 weather:Weather; 2073 week:string; 2074 constructor(weather:Weather, week:string) { 2075 this.weather = weather; 2076 this.week = week; 2077 } 2078} 2079 2080@Entry 2081@Component 2082struct Parent { 2083 @State day1: Day = new Day(new Weather(15), 'Monday'); 2084 2085 build() { 2086 Column({ space:10 }) { 2087 Child({ weather: this.day1.weather}) 2088 } 2089 .height('100%') 2090 .width('100%') 2091 } 2092} 2093 2094@Component 2095struct Child { 2096 @ObjectLink weather: Weather; 2097 2098 reduceTemperature (weather:Weather) { 2099 weather.temperature--; 2100 } 2101 2102 build() { 2103 Column({ space:10 }) { 2104 Text(`The temperature of day1 is ${this.weather.temperature} degrees.`) 2105 .fontSize(20) 2106 Button('increaseTemperature') 2107 .onClick(()=>{ 2108 // 通过赋值添加 Proxy 代理 2109 let weather1 = this.weather; 2110 Weather.increaseTemperature(weather1); 2111 }) 2112 Button('reduceTemperature') 2113 .onClick(()=>{ 2114 // 通过赋值添加 Proxy 代理 2115 let weather2 = this.weather; 2116 this.reduceTemperature(weather2); 2117 }) 2118 } 2119 .height('100%') 2120 .width('100%') 2121 } 2122} 2123``` 2124