1# 状态管理合理使用开发指导 2 3由于对状态管理当前的特性并不了解,许多开发者在使用状态管理进行开发时会遇到UI不刷新、刷新性能差的情况。对此,本篇将从两个方向,对一共五个典型场景进行分析,同时提供相应的正例和反例,帮助开发者学习如何合理使用状态管理进行开发。 4 5## 合理使用属性 6 7### 将简单属性数组合并成对象数组 8 9在开发过程中,我们经常会需要设置多个组件的同一种属性,比如Text组件的内容、组件的宽度、高度等样式信息等。将这些属性保存在一个数组中,配合ForEach进行使用是一种简单且方便的方法。 10 11```typescript 12@Entry 13@Component 14struct Index { 15 @State items: string[] = []; 16 @State ids: string[] = []; 17 @State age: number[] = []; 18 @State gender: string[] = []; 19 20 aboutToAppear() { 21 this.items.push("Head"); 22 this.items.push("List"); 23 for (let i = 0; i < 20; i++) { 24 this.ids.push("id: " + Math.floor(Math.random() * 1000)); 25 this.age.push(Math.floor(Math.random() * 100 % 40)); 26 this.gender.push(Math.floor(Math.random() * 100) % 2 == 0 ? "Male" : "Female"); 27 } 28 } 29 30 isRenderText(index: number) : number { 31 console.log(`index ${index} is rendered`); 32 return 1; 33 } 34 35 build() { 36 Row() { 37 Column() { 38 ForEach(this.items, (item: string) => { 39 if (item == "Head") { 40 Text("Personal Info") 41 .fontSize(40) 42 } else if (item == "List") { 43 List() { 44 ForEach(this.ids, (id: string, index) => { 45 ListItem() { 46 Row() { 47 Text(id) 48 .fontSize(20) 49 .margin({ 50 left: 30, 51 right: 5 52 }) 53 Text("age: " + this.age[index as number]) 54 .fontSize(20) 55 .margin({ 56 left: 5, 57 right: 5 58 }) 59 .position({x: 100}) 60 .opacity(this.isRenderText(index)) 61 .onClick(() => { 62 this.age[index]++; 63 }) 64 Text("gender: " + this.gender[index as number]) 65 .margin({ 66 left: 5, 67 right: 5 68 }) 69 .position({x: 180}) 70 .fontSize(20) 71 } 72 } 73 .margin({ 74 top: 5, 75 bottom: 5 76 }) 77 }) 78 } 79 } 80 }) 81 } 82 } 83 } 84} 85``` 86 87上述代码运行效果如下。 88 89 90 91页面内通过ForEach显示了20条信息,当点击某一条信息中age的Text组件时,可以通过日志发现其他的19条信息中age的Text组件也进行了刷新(这体现在日志上,所有的age的Text组件都打出了日志),但实际上其他19条信息的age的数值并没有改变,也就是说其他19个Text组件并不需要刷新。 92 93这是因为当前状态管理的一个特性。假设存在一个被@State修饰的number类型的数组Num[],其中有20个元素,值分别为0到19。这20个元素分别绑定了一个Text组件,当改变其中一个元素,例如第0号元素的值从0改成1,除了0号元素绑定的Text组件会刷新之外,其他的19个Text组件也会刷新,即使1到19号元素的值并没有改变。 94 95这个特性普遍的出现在简单类型数组的场景中,当数组中的元素够多时,会对UI的刷新性能有很大的负面影响。这种“不需要刷新的组件被刷新”的现象即是“冗余刷新”,当“冗余刷新”的节点过多时,UI的刷新效率会大幅度降低,因此需要减少“冗余刷新”,也就是做到**精准控制组件的更新范围**。 96 97为了减少由简单的属性相关的数组引起的“冗余刷新”,需要将属性数组转变为对象数组,配合自定义组件,实现精准控制更新范围。下面为修改后的代码。 98 99```typescript 100@Observed 101class InfoList extends Array<Info> { 102}; 103@Observed 104class Info { 105 ids: number; 106 age: number; 107 gender: string; 108 109 constructor() { 110 this.ids = Math.floor(Math.random() * 1000); 111 this.age = Math.floor(Math.random() * 100 % 40); 112 this.gender = Math.floor(Math.random() * 100) % 2 == 0 ? "Male" : "Female"; 113 } 114} 115@Component 116struct Information { 117 @ObjectLink info: Info; 118 @State index: number = 0; 119 isRenderText(index: number) : number { 120 console.log(`index ${index} is rendered`); 121 return 1; 122 } 123 124 build() { 125 Row() { 126 Text("id: " + this.info.ids) 127 .fontSize(20) 128 .margin({ 129 left: 30, 130 right: 5 131 }) 132 Text("age: " + this.info.age) 133 .fontSize(20) 134 .margin({ 135 left: 5, 136 right: 5 137 }) 138 .position({x: 100}) 139 .opacity(this.isRenderText(this.index)) 140 .onClick(() => { 141 this.info.age++; 142 }) 143 Text("gender: " + this.info.gender) 144 .margin({ 145 left: 5, 146 right: 5 147 }) 148 .position({x: 180}) 149 .fontSize(20) 150 } 151 } 152} 153@Entry 154@Component 155struct Page { 156 @State infoList: InfoList = new InfoList(); 157 @State items: string[] = []; 158 aboutToAppear() { 159 this.items.push("Head"); 160 this.items.push("List"); 161 for (let i = 0; i < 20; i++) { 162 this.infoList.push(new Info()); 163 } 164 } 165 166 build() { 167 Row() { 168 Column() { 169 ForEach(this.items, (item: string) => { 170 if (item == "Head") { 171 Text("Personal Info") 172 .fontSize(40) 173 } else if (item == "List") { 174 List() { 175 ForEach(this.infoList, (info: Info, index) => { 176 ListItem() { 177 Information({ 178 // in low version, DevEco may throw a warning, but it does not matter. 179 // you can still compile and run. 180 info: info, 181 index: index 182 }) 183 } 184 .margin({ 185 top: 5, 186 bottom: 5 187 }) 188 }) 189 } 190 } 191 }) 192 } 193 } 194 } 195} 196``` 197 198上述代码的运行效果如下。 199 200 201 202修改后的代码使用对象数组代替了原有的多个属性数组,能够避免数组的“冗余刷新”的情况。这是因为对于数组来说,对象内的变化是无法感知的,数组只能观测数组项层级的变化,例如新增数据项,修改数据项(普通数组是直接修改数据项的值,在对象数组的场景下是整个对象被重新赋值,改变某个数据项对象中的属性不会被观测到)、删除数据项等。这意味着当改变对象内的某个属性时,对于数组来说,对象是没有变化的,也就不会去刷新。在当前状态管理的观测能力中,除了数组嵌套对象的场景外,对象嵌套对象的场景也是无法观测到变化的,这一部分内容将在[将复杂对象拆分成多个小对象的集合](#将复杂大对象拆分成多个小对象的集合)中讲到。同时修改代码时使用了自定义组件与ForEach的结合,这一部分内容将在[在ForEach中使用自定义组件搭配对象数组](#在foreach中使用自定义组件搭配对象数组)讲到。 203 204### 将复杂大对象拆分成多个小对象的集合 205 206> **说明:** 207> 208> 从API version 11开始,推荐优先使用[@Track装饰器](arkts-track.md)解决该场景的问题。 209 210在开发过程中,我们有时会定义一个大的对象,其中包含了很多样式相关的属性,并且在父子组件间传递这个对象,将其中的属性绑定在组件上。 211 212```typescript 213@Observed 214class UIStyle { 215 translateX: number = 0; 216 translateY: number = 0; 217 scaleX: number = 0.3; 218 scaleY: number = 0.3; 219 width: number = 336; 220 height: number = 178; 221 posX: number = 10; 222 posY: number = 50; 223 alpha: number = 0.5; 224 borderRadius: number = 24; 225 imageWidth: number = 78; 226 imageHeight: number = 78; 227 translateImageX: number = 0; 228 translateImageY: number = 0; 229 fontSize: number = 20; 230} 231@Component 232struct SpecialImage { 233 @ObjectLink uiStyle: UIStyle; 234 private isRenderSpecialImage() : number { // function to show whether the component is rendered 235 console.log("SpecialImage is rendered"); 236 return 1; 237 } 238 build() { 239 Image($r('app.media.icon')) 240 .width(this.uiStyle.imageWidth) 241 .height(this.uiStyle.imageHeight) 242 .margin({ top: 20 }) 243 .translate({ 244 x: this.uiStyle.translateImageX, 245 y: this.uiStyle.translateImageY 246 }) 247 .opacity(this.isRenderSpecialImage()) // if the Image is rendered, it will call the function 248 } 249} 250@Component 251struct CompA { 252 @ObjectLink uiStyle: UIStyle 253 // the following functions are used to show whether the component is called to be rendered 254 private isRenderColumn() : number { 255 console.log("Column is rendered"); 256 return 1; 257 } 258 private isRenderStack() : number { 259 console.log("Stack is rendered"); 260 return 1; 261 } 262 private isRenderImage() : number { 263 console.log("Image is rendered"); 264 return 1; 265 } 266 private isRenderText() : number { 267 console.log("Text is rendered"); 268 return 1; 269 } 270 build() { 271 Column() { 272 SpecialImage({ 273 // in low version, Dev Eco may throw a warning 274 // But you can still build and run the code 275 uiStyle: this.uiStyle 276 }) 277 Stack() { 278 Column() { 279 Image($r('app.media.icon')) 280 .opacity(this.uiStyle.alpha) 281 .scale({ 282 x: this.uiStyle.scaleX, 283 y: this.uiStyle.scaleY 284 }) 285 .padding(this.isRenderImage()) 286 .width(300) 287 .height(300) 288 } 289 .width('100%') 290 .position({ y: -80 }) 291 Stack() { 292 Text("Hello World") 293 .fontColor("#182431") 294 .fontWeight(FontWeight.Medium) 295 .fontSize(this.uiStyle.fontSize) 296 .opacity(this.isRenderText()) 297 .margin({ top: 12 }) 298 } 299 .opacity(this.isRenderStack()) 300 .position({ 301 x: this.uiStyle.posX, 302 y: this.uiStyle.posY 303 }) 304 .width('100%') 305 .height('100%') 306 } 307 .margin({ top: 50 }) 308 .borderRadius(this.uiStyle.borderRadius) 309 .opacity(this.isRenderStack()) 310 .backgroundColor("#FFFFFF") 311 .width(this.uiStyle.width) 312 .height(this.uiStyle.height) 313 .translate({ 314 x: this.uiStyle.translateX, 315 y: this.uiStyle.translateY 316 }) 317 Column() { 318 Button("Move") 319 .width(312) 320 .fontSize(20) 321 .backgroundColor("#FF007DFF") 322 .margin({ bottom: 10 }) 323 .onClick(() => { 324 animateTo({ 325 duration: 500 326 },() => { 327 this.uiStyle.translateY = (this.uiStyle.translateY + 180) % 250; 328 }) 329 }) 330 Button("Scale") 331 .borderRadius(20) 332 .backgroundColor("#FF007DFF") 333 .fontSize(20) 334 .width(312) 335 .onClick(() => { 336 this.uiStyle.scaleX = (this.uiStyle.scaleX + 0.6) % 0.8; 337 }) 338 } 339 .position({ 340 y:666 341 }) 342 .height('100%') 343 .width('100%') 344 345 } 346 .opacity(this.isRenderColumn()) 347 .width('100%') 348 .height('100%') 349 350 } 351} 352@Entry 353@Component 354struct Page { 355 @State uiStyle: UIStyle = new UIStyle(); 356 build() { 357 Stack() { 358 CompA({ 359 // in low version, Dev Eco may throw a warning 360 // But you can still build and run the code 361 uiStyle: this.uiStyle 362 }) 363 } 364 .backgroundColor("#F1F3F5") 365 } 366} 367``` 368 369上述代码的运行效果如下。 370 371 372 373在上面的示例中,UIStyle定义了多个属性,并且这些属性分别被多个组件关联。当点击任意一个按钮更改其中的某些属性时,会导致所有这些关联uiStyle的组件进行刷新,虽然它们其实并不需要进行刷新(因为组件的属性都没有改变)。通过定义的一系列isRender函数,可以观察到这些组件的刷新。当点击“move”按钮进行平移动画时,由于translateY的值的多次改变,会导致每一次都存在“冗余刷新”的问题,这对应用的性能有着很大的负面影响。 374 375这是因为当前状态管理的一个刷新机制,假设定义了一个有20个属性的类,创建类的对象实例,将20个属性绑定到组件上,这时修改其中的某个属性,除了这个属性关联的组件会刷新之外,其他的19个属性关联的组件也都会刷新,即使这些属性本身并没有发生变化。 376 377这个机制会导致在使用一个复杂大对象与多个组件关联时,刷新性能的下降。对此,推荐将一个复杂大对象拆分成多个小对象的集合,在保留原有代码结构的基础上,减少“冗余刷新”,实现精准控制组件的更新范围。 378 379```typescript 380@Observed 381class NeedRenderImage { // properties only used in the same component can be divided into the same new divided class 382 public translateImageX: number = 0; 383 public translateImageY: number = 0; 384 public imageWidth:number = 78; 385 public imageHeight:number = 78; 386} 387@Observed 388class NeedRenderScale { // properties usually used together can be divided into the same new divided class 389 public scaleX: number = 0.3; 390 public scaleY: number = 0.3; 391} 392@Observed 393class NeedRenderAlpha { // properties that may be used in different places can be divided into the same new divided class 394 public alpha: number = 0.5; 395} 396@Observed 397class NeedRenderSize { // properties usually used together can be divided into the same new divided class 398 public width: number = 336; 399 public height: number = 178; 400} 401@Observed 402class NeedRenderPos { // properties usually used together can be divided into the same new divided class 403 public posX: number = 10; 404 public posY: number = 50; 405} 406@Observed 407class NeedRenderBorderRadius { // properties that may be used in different places can be divided into the same new divided class 408 public borderRadius: number = 24; 409} 410@Observed 411class NeedRenderFontSize { // properties that may be used in different places can be divided into the same new divided class 412 public fontSize: number = 20; 413} 414@Observed 415class NeedRenderTranslate { // properties usually used together can be divided into the same new divided class 416 public translateX: number = 0; 417 public translateY: number = 0; 418} 419@Observed 420class UIStyle { 421 // define new variable instead of using old one 422 needRenderTranslate: NeedRenderTranslate = new NeedRenderTranslate(); 423 needRenderFontSize: NeedRenderFontSize = new NeedRenderFontSize(); 424 needRenderBorderRadius: NeedRenderBorderRadius = new NeedRenderBorderRadius(); 425 needRenderPos: NeedRenderPos = new NeedRenderPos(); 426 needRenderSize: NeedRenderSize = new NeedRenderSize(); 427 needRenderAlpha: NeedRenderAlpha = new NeedRenderAlpha(); 428 needRenderScale: NeedRenderScale = new NeedRenderScale(); 429 needRenderImage: NeedRenderImage = new NeedRenderImage(); 430} 431@Component 432struct SpecialImage { 433 @ObjectLink uiStyle : UIStyle; 434 @ObjectLink needRenderImage: NeedRenderImage // receive the new class from its parent component 435 private isRenderSpecialImage() : number { // function to show whether the component is rendered 436 console.log("SpecialImage is rendered"); 437 return 1; 438 } 439 build() { 440 Image($r('app.media.icon')) 441 .width(this.needRenderImage.imageWidth) // !! use this.needRenderImage.xxx rather than this.uiStyle.needRenderImage.xxx !! 442 .height(this.needRenderImage.imageHeight) 443 .margin({top:20}) 444 .translate({ 445 x: this.needRenderImage.translateImageX, 446 y: this.needRenderImage.translateImageY 447 }) 448 .opacity(this.isRenderSpecialImage()) // if the Image is rendered, it will call the function 449 } 450} 451@Component 452struct CompA { 453 @ObjectLink uiStyle: UIStyle; 454 @ObjectLink needRenderTranslate: NeedRenderTranslate; // receive the new class from its parent component 455 @ObjectLink needRenderFontSize: NeedRenderFontSize; 456 @ObjectLink needRenderBorderRadius: NeedRenderBorderRadius; 457 @ObjectLink needRenderPos: NeedRenderPos; 458 @ObjectLink needRenderSize: NeedRenderSize; 459 @ObjectLink needRenderAlpha: NeedRenderAlpha; 460 @ObjectLink needRenderScale: NeedRenderScale; 461 // the following functions are used to show whether the component is called to be rendered 462 private isRenderColumn() : number { 463 console.log("Column is rendered"); 464 return 1; 465 } 466 private isRenderStack() : number { 467 console.log("Stack is rendered"); 468 return 1; 469 } 470 private isRenderImage() : number { 471 console.log("Image is rendered"); 472 return 1; 473 } 474 private isRenderText() : number { 475 console.log("Text is rendered"); 476 return 1; 477 } 478 build() { 479 Column() { 480 SpecialImage({ 481 // in low version, Dev Eco may throw a warning 482 // But you can still build and run the code 483 uiStyle: this.uiStyle, 484 needRenderImage: this.uiStyle.needRenderImage //send it to its child 485 }) 486 Stack() { 487 Column() { 488 Image($r('app.media.icon')) 489 .opacity(this.needRenderAlpha.alpha) 490 .scale({ 491 x: this.needRenderScale.scaleX, // use this.needRenderXxx.xxx rather than this.uiStyle.needRenderXxx.xxx 492 y: this.needRenderScale.scaleY 493 }) 494 .padding(this.isRenderImage()) 495 .width(300) 496 .height(300) 497 } 498 .width('100%') 499 .position({ y: -80 }) 500 501 Stack() { 502 Text("Hello World") 503 .fontColor("#182431") 504 .fontWeight(FontWeight.Medium) 505 .fontSize(this.needRenderFontSize.fontSize) 506 .opacity(this.isRenderText()) 507 .margin({ top: 12 }) 508 } 509 .opacity(this.isRenderStack()) 510 .position({ 511 x: this.needRenderPos.posX, 512 y: this.needRenderPos.posY 513 }) 514 .width('100%') 515 .height('100%') 516 } 517 .margin({ top: 50 }) 518 .borderRadius(this.needRenderBorderRadius.borderRadius) 519 .opacity(this.isRenderStack()) 520 .backgroundColor("#FFFFFF") 521 .width(this.needRenderSize.width) 522 .height(this.needRenderSize.height) 523 .translate({ 524 x: this.needRenderTranslate.translateX, 525 y: this.needRenderTranslate.translateY 526 }) 527 528 Column() { 529 Button("Move") 530 .width(312) 531 .fontSize(20) 532 .backgroundColor("#FF007DFF") 533 .margin({ bottom: 10 }) 534 .onClick(() => { 535 animateTo({ 536 duration: 500 537 }, () => { 538 this.needRenderTranslate.translateY = (this.needRenderTranslate.translateY + 180) % 250; 539 }) 540 }) 541 Button("Scale") 542 .borderRadius(20) 543 .backgroundColor("#FF007DFF") 544 .fontSize(20) 545 .width(312) 546 .margin({ bottom: 10 }) 547 .onClick(() => { 548 this.needRenderScale.scaleX = (this.needRenderScale.scaleX + 0.6) % 0.8; 549 }) 550 Button("Change Image") 551 .borderRadius(20) 552 .backgroundColor("#FF007DFF") 553 .fontSize(20) 554 .width(312) 555 .onClick(() => { // in the parent component, still use this.uiStyle.needRenderXxx.xxx to change the properties 556 this.uiStyle.needRenderImage.imageWidth = (this.uiStyle.needRenderImage.imageWidth + 30) % 160; 557 this.uiStyle.needRenderImage.imageHeight = (this.uiStyle.needRenderImage.imageHeight + 30) % 160; 558 }) 559 } 560 .position({ 561 y: 616 562 }) 563 .height('100%') 564 .width('100%') 565 } 566 .opacity(this.isRenderColumn()) 567 .width('100%') 568 .height('100%') 569 } 570} 571@Entry 572@Component 573struct Page { 574 @State uiStyle: UIStyle = new UIStyle(); 575 build() { 576 Stack() { 577 CompA({ 578 // in low version, Dev Eco may throw a warning 579 // But you can still build and run the code 580 uiStyle: this.uiStyle, 581 needRenderTranslate: this.uiStyle.needRenderTranslate, //send all the new class child need 582 needRenderFontSize: this.uiStyle.needRenderFontSize, 583 needRenderBorderRadius: this.uiStyle.needRenderBorderRadius, 584 needRenderPos: this.uiStyle.needRenderPos, 585 needRenderSize: this.uiStyle.needRenderSize, 586 needRenderAlpha: this.uiStyle.needRenderAlpha, 587 needRenderScale: this.uiStyle.needRenderScale 588 }) 589 } 590 .backgroundColor("#F1F3F5") 591 } 592} 593``` 594 595上述代码的运行效果如下。 596 597修改后的代码将原来的大类中的十五个属性拆成了八个小类,并且在绑定的组件上也做了相应的适配。属性拆分遵循以下几点原则: 598 599- 只作用在同一个组件上的多个属性可以被拆分进同一个新类,即示例中的NeedRenderImage。适用于组件经常被不关联的属性改变而引起刷新的场景,这个时候就要考虑拆分属性,或者重新考虑ViewModel设计是否合理。 600- 经常被同时使用的属性可以被拆分进同一个新类,即示例中的NeedRenderScale、NeedRenderTranslate、NeedRenderPos、NeedRenderSize。适用于属性经常成对出现,或者被作用在同一个样式上的情况,例如.translate、.position、.scale等(这些样式通常会接收一个对象作为参数)。 601- 可能被用在多个组件上或相对较独立的属性应该被单独拆分进一个新类,即示例中的NeedRenderAlpha,NeedRenderBorderRadius、NeedRenderFontSize。适用于一个属性作用在多个组件上或者与其他属性没有联系的情况,例如.opacity、.borderRadius等(这些样式通常相对独立)。 602 603属性拆分的原理和属性合并类似,都是在嵌套场景下,状态管理无法观测二层以上的属性变化,所以不会因为二层的数据变化导致一层关联的其他属性被刷新,同时利用@Observed和@ObjectLink在父子节点间传递二层的对象,从而在子组件中正常的观测二层的数据变化,实现精准刷新。关于属性拆分的详细内容,可以查看[精准控制组件的更新范围](../performance/precisely-control-render-scope.md)。 604 605使用@Track装饰器则无需做属性拆分,也能达到同样控制组件更新范围的作用。 606 607```ts 608@Observed 609class UIStyle { 610 @Track translateX: number = 0; 611 @Track translateY: number = 0; 612 @Track scaleX: number = 0.3; 613 @Track scaleY: number = 0.3; 614 @Track width: number = 336; 615 @Track height: number = 178; 616 @Track posX: number = 10; 617 @Track posY: number = 50; 618 @Track alpha: number = 0.5; 619 @Track borderRadius: number = 24; 620 @Track imageWidth: number = 78; 621 @Track imageHeight: number = 78; 622 @Track translateImageX: number = 0; 623 @Track translateImageY: number = 0; 624 @Track fontSize: number = 20; 625} 626@Component 627struct SpecialImage { 628 @ObjectLink uiStyle: UIStyle; 629 private isRenderSpecialImage() : number { // function to show whether the component is rendered 630 console.log("SpecialImage is rendered"); 631 return 1; 632 } 633 build() { 634 Image($r('app.media.icon')) 635 .width(this.uiStyle.imageWidth) 636 .height(this.uiStyle.imageHeight) 637 .margin({ top: 20 }) 638 .translate({ 639 x: this.uiStyle.translateImageX, 640 y: this.uiStyle.translateImageY 641 }) 642 .opacity(this.isRenderSpecialImage()) // if the Image is rendered, it will call the function 643 } 644} 645@Component 646struct CompA { 647 @ObjectLink uiStyle: UIStyle 648 // the following functions are used to show whether the component is called to be rendered 649 private isRenderColumn() : number { 650 console.log("Column is rendered"); 651 return 1; 652 } 653 private isRenderStack() : number { 654 console.log("Stack is rendered"); 655 return 1; 656 } 657 private isRenderImage() : number { 658 console.log("Image is rendered"); 659 return 1; 660 } 661 private isRenderText() : number { 662 console.log("Text is rendered"); 663 return 1; 664 } 665 build() { 666 Column() { 667 SpecialImage({ 668 // in low version, Dev Eco may throw a warning 669 // But you can still build and run the code 670 uiStyle: this.uiStyle 671 }) 672 Stack() { 673 Column() { 674 Image($r('app.media.icon')) 675 .opacity(this.uiStyle.alpha) 676 .scale({ 677 x: this.uiStyle.scaleX, 678 y: this.uiStyle.scaleY 679 }) 680 .padding(this.isRenderImage()) 681 .width(300) 682 .height(300) 683 } 684 .width('100%') 685 .position({ y: -80 }) 686 Stack() { 687 Text("Hello World") 688 .fontColor("#182431") 689 .fontWeight(FontWeight.Medium) 690 .fontSize(this.uiStyle.fontSize) 691 .opacity(this.isRenderText()) 692 .margin({ top: 12 }) 693 } 694 .opacity(this.isRenderStack()) 695 .position({ 696 x: this.uiStyle.posX, 697 y: this.uiStyle.posY 698 }) 699 .width('100%') 700 .height('100%') 701 } 702 .margin({ top: 50 }) 703 .borderRadius(this.uiStyle.borderRadius) 704 .opacity(this.isRenderStack()) 705 .backgroundColor("#FFFFFF") 706 .width(this.uiStyle.width) 707 .height(this.uiStyle.height) 708 .translate({ 709 x: this.uiStyle.translateX, 710 y: this.uiStyle.translateY 711 }) 712 Column() { 713 Button("Move") 714 .width(312) 715 .fontSize(20) 716 .backgroundColor("#FF007DFF") 717 .margin({ bottom: 10 }) 718 .onClick(() => { 719 animateTo({ 720 duration: 500 721 },() => { 722 this.uiStyle.translateY = (this.uiStyle.translateY + 180) % 250; 723 }) 724 }) 725 Button("Scale") 726 .borderRadius(20) 727 .backgroundColor("#FF007DFF") 728 .fontSize(20) 729 .width(312) 730 .onClick(() => { 731 this.uiStyle.scaleX = (this.uiStyle.scaleX + 0.6) % 0.8; 732 }) 733 } 734 .position({ 735 y:666 736 }) 737 .height('100%') 738 .width('100%') 739 740 } 741 .opacity(this.isRenderColumn()) 742 .width('100%') 743 .height('100%') 744 745 } 746} 747@Entry 748@Component 749struct Page { 750 @State uiStyle: UIStyle = new UIStyle(); 751 build() { 752 Stack() { 753 CompA({ 754 // in low version, Dev Eco may throw a warning 755 // But you can still build and run the code 756 uiStyle: this.uiStyle 757 }) 758 } 759 .backgroundColor("#F1F3F5") 760 } 761} 762``` 763 764 765 766### 使用@Observed装饰或被声明为状态变量的类对象绑定组件 767 768在开发过程中,会有“重置数据”的场景,将一个新创建的对象赋值给原有的状态变量,实现数据的刷新。如果不注意新创建对象的类型,可能会出现UI不刷新的现象。 769 770```typescript 771@Observed 772class Child { 773 count: number; 774 constructor(count: number) { 775 this.count = count 776 } 777} 778@Observed 779class ChildList extends Array<Child> { 780}; 781@Observed 782class Ancestor { 783 childList: ChildList; 784 constructor(childList: ChildList) { 785 this.childList = childList; 786 } 787 public loadData() { 788 let tempList = [new Child(1), new Child(2), new Child(3), new Child(4), new Child(5)]; 789 this.childList = tempList; 790 } 791 792 public clearData() { 793 this.childList = [] 794 } 795} 796@Component 797struct CompChild { 798 @Link childList: ChildList; 799 @ObjectLink child: Child; 800 801 build() { 802 Row() { 803 Text(this.child.count+'') 804 .height(70) 805 .fontSize(20) 806 .borderRadius({ 807 topLeft: 6, 808 topRight: 6 809 }) 810 .margin({left: 50}) 811 Button('X') 812 .backgroundColor(Color.Red) 813 .onClick(()=>{ 814 let index = this.childList.findIndex((item) => { 815 return item.count === this.child.count 816 }) 817 if (index !== -1) { 818 this.childList.splice(index, 1); 819 } 820 }) 821 .margin({ 822 left: 200, 823 right:30 824 }) 825 } 826 .margin({ 827 top:15, 828 left: 15, 829 right:10, 830 bottom:15 831 }) 832 .borderRadius(6) 833 .backgroundColor(Color.Grey) 834 } 835} 836@Component 837struct CompList { 838 @ObjectLink@Watch('changeChildList') childList: ChildList; 839 840 changeChildList() { 841 console.log('CompList ChildList change'); 842 } 843 844 isRenderCompChild(index: number) : number { 845 console.log("Comp Child is render" + index); 846 return 1; 847 } 848 849 build() { 850 Column() { 851 List() { 852 ForEach(this.childList, (item: Child, index) => { 853 ListItem() { 854 // in low version, Dev Eco may throw a warning 855 // But you can still build and run the code 856 CompChild({ 857 childList: this.childList, 858 child: item 859 }) 860 .opacity(this.isRenderCompChild(index)) 861 } 862 863 }) 864 } 865 .height('70%') 866 } 867 } 868} 869@Component 870struct CompAncestor { 871 @ObjectLink ancestor: Ancestor; 872 873 build() { 874 Column() { 875 // in low version, Dev Eco may throw a warning 876 // But you can still build and run the code 877 CompList({ childList: this.ancestor.childList }) 878 Row() { 879 Button("Clear") 880 .onClick(() => { 881 this.ancestor.clearData() 882 }) 883 .width(100) 884 .margin({right: 50}) 885 Button("Recover") 886 .onClick(() => { 887 this.ancestor.loadData() 888 }) 889 .width(100) 890 } 891 } 892 } 893} 894@Entry 895@Component 896struct Page { 897 @State childList: ChildList = [new Child(1), new Child(2), new Child(3), new Child(4),new Child(5)]; 898 @State ancestor: Ancestor = new Ancestor(this.childList) 899 900 build() { 901 Column() { 902 // in low version, Dev Eco may throw a warning 903 // But you can still build and run the code 904 CompAncestor({ ancestor: this.ancestor}) 905 } 906 } 907} 908``` 909 910上述代码运行效果如下。 911 912 913 914上述代码维护了一个ChildList类型的数据源,点击"X"按钮删除一些数据后再点击Recover进行恢复ChildList,发现再次点击"X"按钮进行删除时,UI并没有刷新,同时也没有打印出“CompList ChildList change”的日志。 915 916代码中对数据源childList重新赋值时,是通过Ancestor对象的方法loadData。 917 918```typescript 919 public loadData() { 920 let tempList = [new Child(1), new Child(2), new Child(3), new Child(4), new Child(5)]; 921 this.childList = tempList; 922 } 923``` 924 925在loadData方法中,创建了一个临时的Child类型的数组tempList,并且将Ancestor对象的成员变量的childList指向了tempList。但是这里创建的Child[]类型的数组tempList其实并没有能被观测的能力(也就说它的变化无法主动触发UI刷新)。当它被赋值给childList之后,触发了ForEach的刷新,使得界面完成了重建,但是再次点击删除时,由于此时的childList已经指向了新的tempList代表的数组,并且这个数组并没有被观测的能力,是个静态的量,所以它的更改不会被观测到,也就不会引起UI的刷新。实际上这个时候childList里的数据已经减少了,只是UI没有刷新。 926 927有些开发者会注意到,在Page中初始化定义childList的时候,也是以这样一种方法去进行初始化的。 928 929```typescript 930@State childList: ChildList = [new Child(1), new Child(2), new Child(3), new Child(4),new Child(5)]; 931@State ancestor: Ancestor = new Ancestor(this.childList) 932``` 933 934但是由于这里的childList实际上是被@State装饰了,根据当前状态管理的观测能力,尽管右边赋值的是一个Child[]类型的数据,它并没有被@Observed装饰,这里的childList却依然具备了被观测的能力,所以能够正常的触发UI的刷新。当去掉childList的@State的装饰器后,不去重置数据源,也无法通过点击“X”按钮触发刷新。 935 936因此,需要将具有观测能力的类对象绑定组件,来确保当改变这些类对象的内容时,UI能够正常的刷新。 937 938```typescript 939@Observed 940class Child { 941 count: number; 942 constructor(count: number) { 943 this.count = count 944 } 945} 946@Observed 947class ChildList extends Array<Child> { 948}; 949@Observed 950class Ancestor { 951 childList: ChildList; 952 constructor(childList: ChildList) { 953 this.childList = childList; 954 } 955 public loadData() { 956 let tempList = new ChildList(); 957 for (let i = 1; i < 6; i ++) { 958 tempList.push(new Child(i)); 959 } 960 this.childList = tempList; 961 } 962 963 public clearData() { 964 this.childList = [] 965 } 966} 967@Component 968struct CompChild { 969 @Link childList: ChildList; 970 @ObjectLink child: Child; 971 972 build() { 973 Row() { 974 Text(this.child.count+'') 975 .height(70) 976 .fontSize(20) 977 .borderRadius({ 978 topLeft: 6, 979 topRight: 6 980 }) 981 .margin({left: 50}) 982 Button('X') 983 .backgroundColor(Color.Red) 984 .onClick(()=>{ 985 let index = this.childList.findIndex((item) => { 986 return item.count === this.child.count 987 }) 988 if (index !== -1) { 989 this.childList.splice(index, 1); 990 } 991 }) 992 .margin({ 993 left: 200, 994 right:30 995 }) 996 } 997 .margin({ 998 top:15, 999 left: 15, 1000 right:10, 1001 bottom:15 1002 }) 1003 .borderRadius(6) 1004 .backgroundColor(Color.Grey) 1005 } 1006} 1007@Component 1008struct CompList { 1009 @ObjectLink@Watch('changeChildList') childList: ChildList; 1010 1011 changeChildList() { 1012 console.log('CompList ChildList change'); 1013 } 1014 1015 isRenderCompChild(index: number) : number { 1016 console.log("Comp Child is render" + index); 1017 return 1; 1018 } 1019 1020 build() { 1021 Column() { 1022 List() { 1023 ForEach(this.childList, (item: Child, index) => { 1024 ListItem() { 1025 // in low version, Dev Eco may throw a warning 1026 // But you can still build and run the code 1027 CompChild({ 1028 childList: this.childList, 1029 child: item 1030 }) 1031 .opacity(this.isRenderCompChild(index)) 1032 } 1033 1034 }) 1035 } 1036 .height('70%') 1037 } 1038 } 1039} 1040@Component 1041struct CompAncestor { 1042 @ObjectLink ancestor: Ancestor; 1043 1044 build() { 1045 Column() { 1046 // in low version, Dev Eco may throw a warning 1047 // But you can still build and run the code 1048 CompList({ childList: this.ancestor.childList }) 1049 Row() { 1050 Button("Clear") 1051 .onClick(() => { 1052 this.ancestor.clearData() 1053 }) 1054 .width(100) 1055 .margin({right: 50}) 1056 Button("Recover") 1057 .onClick(() => { 1058 this.ancestor.loadData() 1059 }) 1060 .width(100) 1061 } 1062 } 1063 } 1064} 1065@Entry 1066@Component 1067struct Page { 1068 @State childList: ChildList = [new Child(1), new Child(2), new Child(3), new Child(4),new Child(5)]; 1069 @State ancestor: Ancestor = new Ancestor(this.childList) 1070 1071 build() { 1072 Column() { 1073 // in low version, Dev Eco may throw a warning 1074 // But you can still build and run the code 1075 CompAncestor({ ancestor: this.ancestor}) 1076 } 1077 } 1078} 1079``` 1080 1081上述代码运行效果如下。 1082 1083 1084 1085核心的修改点是将原本Child[]类型的tempList修改为具有被观测能力的ChildList类。 1086 1087```typescript 1088public loadData() { 1089 let tempList = new ChildList(); 1090 for (let i = 1; i < 6; i ++) { 1091 tempList.push(new Child(i)); 1092 } 1093 this.childList = tempList; 1094 } 1095``` 1096 1097ChildList类型在定义的时候使用了@Observed进行装饰,所以用new创建的对象tempList具有被观测的能力,因此在点击“X”按钮删除其中一条内容时,变量childList就能够观测到变化,所以触发了ForEach的刷新,最终UI渲染刷新。 1098 1099## 合理使用ForEach/LazyForEach 1100 1101### 减少使用LazyForEach的重建机制刷新UI 1102 1103开发过程中通常会将LazyForEach和状态变量结合起来使用。 1104 1105```typescript 1106class BasicDataSource implements IDataSource { 1107 private listeners: DataChangeListener[] = []; 1108 private originDataArray: StringData[] = []; 1109 1110 public totalCount(): number { 1111 return 0; 1112 } 1113 1114 public getData(index: number): StringData { 1115 return this.originDataArray[index]; 1116 } 1117 1118 registerDataChangeListener(listener: DataChangeListener): void { 1119 if (this.listeners.indexOf(listener) < 0) { 1120 console.info('add listener'); 1121 this.listeners.push(listener); 1122 } 1123 } 1124 1125 unregisterDataChangeListener(listener: DataChangeListener): void { 1126 const pos = this.listeners.indexOf(listener); 1127 if (pos >= 0) { 1128 console.info('remove listener'); 1129 this.listeners.splice(pos, 1); 1130 } 1131 } 1132 1133 notifyDataReload(): void { 1134 this.listeners.forEach(listener => { 1135 listener.onDataReloaded(); 1136 }) 1137 } 1138 1139 notifyDataAdd(index: number): void { 1140 this.listeners.forEach(listener => { 1141 listener.onDataAdd(index); 1142 }) 1143 } 1144 1145 notifyDataChange(index: number): void { 1146 this.listeners.forEach(listener => { 1147 listener.onDataChange(index); 1148 }) 1149 } 1150 1151 notifyDataDelete(index: number): void { 1152 this.listeners.forEach(listener => { 1153 listener.onDataDelete(index); 1154 }) 1155 } 1156 1157 notifyDataMove(from: number, to: number): void { 1158 this.listeners.forEach(listener => { 1159 listener.onDataMove(from, to); 1160 }) 1161 } 1162} 1163 1164class MyDataSource extends BasicDataSource { 1165 private dataArray: StringData[] = []; 1166 1167 public totalCount(): number { 1168 return this.dataArray.length; 1169 } 1170 1171 public getData(index: number): StringData { 1172 return this.dataArray[index]; 1173 } 1174 1175 public addData(index: number, data: StringData): void { 1176 this.dataArray.splice(index, 0, data); 1177 this.notifyDataAdd(index); 1178 } 1179 1180 public pushData(data: StringData): void { 1181 this.dataArray.push(data); 1182 this.notifyDataAdd(this.dataArray.length - 1); 1183 } 1184 1185 public reloadData(): void { 1186 this.notifyDataReload(); 1187 } 1188} 1189 1190class StringData { 1191 message: string; 1192 imgSrc: Resource; 1193 constructor(message: string, imgSrc: Resource) { 1194 this.message = message; 1195 this.imgSrc = imgSrc; 1196 } 1197} 1198 1199@Entry 1200@Component 1201struct MyComponent { 1202 private data: MyDataSource = new MyDataSource(); 1203 1204 aboutToAppear() { 1205 for (let i = 0; i <= 9; i++) { 1206 this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); 1207 } 1208 } 1209 1210 build() { 1211 List({ space: 3 }) { 1212 LazyForEach(this.data, (item: StringData, index: number) => { 1213 ListItem() { 1214 Column() { 1215 Text(item.message).fontSize(20) 1216 .onAppear(() => { 1217 console.info("text appear:" + item.message); 1218 }) 1219 Image(item.imgSrc) 1220 .width(100) 1221 .height(100) 1222 .onAppear(() => { 1223 console.info("image appear"); 1224 }) 1225 }.margin({ left: 10, right: 10 }) 1226 } 1227 .onClick(() => { 1228 item.message += '0'; 1229 this.data.reloadData(); 1230 }) 1231 }, (item: StringData, index: number) => JSON.stringify(item)) 1232 }.cachedCount(5) 1233 } 1234} 1235``` 1236 1237上述代码运行效果如下。 1238 1239 1240 1241可以观察到在点击更改message之后,图片“闪烁”了一下,同时输出了组件的onAppear日志,这说明组件进行了重建。这是因为在更改message之后,导致LazyForEach中这一项的key值发生了变化,使得LazyForEach在reloadData的时候将这一项ListItem进行了重建。Text组件仅仅更改显示的内容却发生了重建,而不是更新。而尽管Image组件没有需要重新绘制的内容,但是因为触发LazyForEach的重建,会使得同样位于ListItem下的Image组件重新创建。 1242 1243当前LazyForEach与状态变量都能触发UI的刷新,两者的性能开销是不一样的。使用LazyForEach刷新会对组件进行重建,如果包含了多个组件,则会产生比较大的性能开销。使用状态变量刷新会对组件进行刷新,具体到状态变量关联的组件上,相对于LazyForEach的重建来说,范围更小更精确。因此,推荐使用状态变量来触发LazyForEach中的组件刷新,这就需要使用自定义组件。 1244 1245```typescript 1246class BasicDataSource implements IDataSource { 1247 private listeners: DataChangeListener[] = []; 1248 private originDataArray: StringData[] = []; 1249 1250 public totalCount(): number { 1251 return 0; 1252 } 1253 1254 public getData(index: number): StringData { 1255 return this.originDataArray[index]; 1256 } 1257 1258 registerDataChangeListener(listener: DataChangeListener): void { 1259 if (this.listeners.indexOf(listener) < 0) { 1260 console.info('add listener'); 1261 this.listeners.push(listener); 1262 } 1263 } 1264 1265 unregisterDataChangeListener(listener: DataChangeListener): void { 1266 const pos = this.listeners.indexOf(listener); 1267 if (pos >= 0) { 1268 console.info('remove listener'); 1269 this.listeners.splice(pos, 1); 1270 } 1271 } 1272 1273 notifyDataReload(): void { 1274 this.listeners.forEach(listener => { 1275 listener.onDataReloaded(); 1276 }) 1277 } 1278 1279 notifyDataAdd(index: number): void { 1280 this.listeners.forEach(listener => { 1281 listener.onDataAdd(index); 1282 }) 1283 } 1284 1285 notifyDataChange(index: number): void { 1286 this.listeners.forEach(listener => { 1287 listener.onDataChange(index); 1288 }) 1289 } 1290 1291 notifyDataDelete(index: number): void { 1292 this.listeners.forEach(listener => { 1293 listener.onDataDelete(index); 1294 }) 1295 } 1296 1297 notifyDataMove(from: number, to: number): void { 1298 this.listeners.forEach(listener => { 1299 listener.onDataMove(from, to); 1300 }) 1301 } 1302} 1303 1304class MyDataSource extends BasicDataSource { 1305 private dataArray: StringData[] = []; 1306 1307 public totalCount(): number { 1308 return this.dataArray.length; 1309 } 1310 1311 public getData(index: number): StringData { 1312 return this.dataArray[index]; 1313 } 1314 1315 public addData(index: number, data: StringData): void { 1316 this.dataArray.splice(index, 0, data); 1317 this.notifyDataAdd(index); 1318 } 1319 1320 public pushData(data: StringData): void { 1321 this.dataArray.push(data); 1322 this.notifyDataAdd(this.dataArray.length - 1); 1323 } 1324} 1325 1326@Observed 1327class StringData { 1328 @Track message: string; 1329 @Track imgSrc: Resource; 1330 constructor(message: string, imgSrc: Resource) { 1331 this.message = message; 1332 this.imgSrc = imgSrc; 1333 } 1334} 1335 1336@Entry 1337@Component 1338struct MyComponent { 1339 @State data: MyDataSource = new MyDataSource(); 1340 1341 aboutToAppear() { 1342 for (let i = 0; i <= 9; i++) { 1343 this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); 1344 } 1345 } 1346 1347 build() { 1348 List({ space: 3 }) { 1349 LazyForEach(this.data, (item: StringData, index: number) => { 1350 ListItem() { 1351 // in low version, Dev Eco may throw a warning 1352 // But you can still build and run the code 1353 ChildComponent({data: item}) 1354 } 1355 .onClick(() => { 1356 item.message += '0'; 1357 }) 1358 }, (item: StringData, index: number) => index.toString()) 1359 }.cachedCount(5) 1360 } 1361} 1362 1363@Component 1364struct ChildComponent { 1365 @ObjectLink data: StringData 1366 build() { 1367 Column() { 1368 Text(this.data.message).fontSize(20) 1369 .onAppear(() => { 1370 console.info("text appear:" + this.data.message) 1371 }) 1372 Image(this.data.imgSrc) 1373 .width(100) 1374 .height(100) 1375 }.margin({ left: 10, right: 10 }) 1376 } 1377} 1378``` 1379 1380上述代码运行效果如下。 1381 1382 1383 1384可以观察到UI能够正常刷新,图片没有“闪烁”,且没有输出日志信息,说明没有对Text组件和Image组件进行重建。 1385 1386这是因为使用自定义组件之后,可以通过@Observed和@ObjectLink配合去直接更改自定义组件内的状态变量实现刷新,而不需要利用LazyForEach进行重建。使用[@Track装饰器](arkts-track.md)分别装饰StringData类型中的message和imgSrc属性可以使更新范围进一步缩小到指定的Text组件。 1387 1388### 在ForEach中使用自定义组件搭配对象数组 1389 1390开发过程中经常会使用对象数组和ForEach结合起来使用,但是写法不当的话会出现UI不刷新的情况。 1391 1392```typescript 1393@Observed 1394class StyleList extends Array<TextStyle> { 1395}; 1396@Observed 1397class TextStyle { 1398 fontSize: number; 1399 1400 constructor(fontSize: number) { 1401 this.fontSize = fontSize; 1402 } 1403} 1404@Entry 1405@Component 1406struct Page { 1407 @State styleList: StyleList = new StyleList(); 1408 aboutToAppear() { 1409 for (let i = 15; i < 50; i++) 1410 this.styleList.push(new TextStyle(i)); 1411 } 1412 build() { 1413 Column() { 1414 Text("Font Size List") 1415 .fontSize(50) 1416 .onClick(() => { 1417 for (let i = 0; i < this.styleList.length; i++) { 1418 this.styleList[i].fontSize++; 1419 } 1420 console.log("change font size"); 1421 }) 1422 List() { 1423 ForEach(this.styleList, (item: TextStyle) => { 1424 ListItem() { 1425 Text("Hello World") 1426 .fontSize(item.fontSize) 1427 } 1428 }) 1429 } 1430 } 1431 } 1432} 1433``` 1434 1435上述代码运行效果如下。 1436 1437 1438 1439由于ForEach中生成的item是一个常量,因此当点击改变item中的内容时,没有办法观测到UI刷新,尽管日志表面item中的值已经改变了(这体现在打印了“change font size”的日志)。因此,需要使用自定义组件,配合@ObjectLink来实现观测的能力。 1440 1441```typescript 1442@Observed 1443class StyleList extends Array<TextStyle> { 1444}; 1445@Observed 1446class TextStyle { 1447 fontSize: number; 1448 1449 constructor(fontSize: number) { 1450 this.fontSize = fontSize; 1451 } 1452} 1453@Component 1454struct TextComponent { 1455 @ObjectLink textStyle: TextStyle; 1456 build() { 1457 Text("Hello World") 1458 .fontSize(this.textStyle.fontSize) 1459 } 1460} 1461@Entry 1462@Component 1463struct Page { 1464 @State styleList: StyleList = new StyleList(); 1465 aboutToAppear() { 1466 for (let i = 15; i < 50; i++) 1467 this.styleList.push(new TextStyle(i)); 1468 } 1469 build() { 1470 Column() { 1471 Text("Font Size List") 1472 .fontSize(50) 1473 .onClick(() => { 1474 for (let i = 0; i < this.styleList.length; i++) { 1475 this.styleList[i].fontSize++; 1476 } 1477 console.log("change font size"); 1478 }) 1479 List() { 1480 ForEach(this.styleList, (item: TextStyle) => { 1481 ListItem() { 1482 // in low version, Dev Eco may throw a warning 1483 // But you can still build and run the code 1484 TextComponent({ textStyle: item}) 1485 } 1486 }) 1487 } 1488 } 1489 } 1490} 1491``` 1492 1493上述代码的运行效果如下。 1494 1495 1496 1497使用@ObjectLink接受传入的item后,使得TextComponent组件内的textStyle变量具有了被观测的能力。在父组件更改styleList中的值时,由于@ObjectLink是引用传递,所以会观测到styleList每一个数据项的地址指向的对应item的fontSize的值被改变,因此触发UI的刷新。 1498 1499这是一个较为实用的使用状态管理进行刷新的开发方式。 1500 1501 1502 1503<!--no_check-->