首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

HarmonyOS开发实战( Beta5版)状态管理合理使用开发实践指导

  • 25-03-03 06:42
  • 3323
  • 8954
blog.csdn.net

由于对状态管理当前的特性并不了解,许多开发者在使用状态管理进行开发时会遇到UI不刷新、刷新性能差的情况。对此,本篇将从两个方向,对一共五个典型场景进行分析,同时提供相应的正例和反例,帮助开发者学习如何合理使用状态管理进行开发。

合理使用属性

将简单属性数组合并成对象数组

在开发过程中,我们经常会需要设置多个组件的同一种属性,比如Text组件的内容、组件的宽度、高度等样式信息等。将这些属性保存在一个数组中,配合ForEach进行使用是一种简单且方便的方法。GitCode - 全球开发者的开源社区,开源代码托管平台

  1. @Entry
  2. @Component
  3. struct Index {
  4. @State items: string[] = [];
  5. @State ids: string[] = [];
  6. @State age: number[] = [];
  7. @State gender: string[] = [];
  8. aboutToAppear() {
  9. this.items.push("Head");
  10. this.items.push("List");
  11. for (let i = 0; i < 20; i++) {
  12. this.ids.push("id: " + Math.floor(Math.random() * 1000));
  13. this.age.push(Math.floor(Math.random() * 100 % 40));
  14. this.gender.push(Math.floor(Math.random() * 100) % 2 == 0 ? "Male" : "Female");
  15. }
  16. }
  17. isRenderText(index: number) : number {
  18. console.info(`index ${index} is rendered`);
  19. return 1;
  20. }
  21. build() {
  22. Row() {
  23. Column() {
  24. ForEach(this.items, (item: string) => {
  25. if (item == "Head") {
  26. Text("Personal Info")
  27. .fontSize(40)
  28. } else if (item == "List") {
  29. List() {
  30. ForEach(this.ids, (id: string, index) => {
  31. ListItem() {
  32. Row() {
  33. Text(id)
  34. .fontSize(20)
  35. .margin({
  36. left: 30,
  37. right: 5
  38. })
  39. Text("age: " + this.age[index as number])
  40. .fontSize(20)
  41. .margin({
  42. left: 5,
  43. right: 5
  44. })
  45. .position({x: 100})
  46. .opacity(this.isRenderText(index))
  47. .onClick(() => {
  48. this.age[index]++;
  49. })
  50. Text("gender: " + this.gender[index as number])
  51. .margin({
  52. left: 5,
  53. right: 5
  54. })
  55. .position({x: 180})
  56. .fontSize(20)
  57. }
  58. }
  59. .margin({
  60. top: 5,
  61. bottom: 5
  62. })
  63. })
  64. }
  65. }
  66. })
  67. }
  68. }
  69. }
  70. }

上述代码运行效果如下。

properly-use-state-management-to-develope-1

页面内通过ForEach显示了20条信息,当点击某一条信息中age的Text组件时,可以通过日志发现其他的19条信息中age的Text组件也进行了刷新(这体现在日志上,所有的age的Text组件都打出了日志),但实际上其他19条信息的age的数值并没有改变,也就是说其他19个Text组件并不需要刷新。

这是因为当前状态管理的一个特性。假设存在一个被@State修饰的number类型的数组Num[],其中有20个元素,值分别为0到19。这20个元素分别绑定了一个Text组件,当改变其中一个元素,例如第0号元素的值从0改成1,除了0号元素绑定的Text组件会刷新之外,其他的19个Text组件也会刷新,即使1到19号元素的值并没有改变。

这个特性普遍的出现在简单类型数组的场景中,当数组中的元素够多时,会对UI的刷新性能有很大的负面影响。这种“不需要刷新的组件被刷新”的现象即是“冗余刷新”,当“冗余刷新”的节点过多时,UI的刷新效率会大幅度降低,因此需要减少“冗余刷新”,也就是做到精准控制组件的更新范围。

为了减少由简单的属性相关的数组引起的“冗余刷新”,需要将属性数组转变为对象数组,配合自定义组件,实现精准控制更新范围。下面为修改后的代码。

  1. @Observed
  2. class InfoList extends Array<Info> {
  3. };
  4. @Observed
  5. class Info {
  6. ids: number;
  7. age: number;
  8. gender: string;
  9. constructor() {
  10. this.ids = Math.floor(Math.random() * 1000);
  11. this.age = Math.floor(Math.random() * 100 % 40);
  12. this.gender = Math.floor(Math.random() * 100) % 2 == 0 ? "Male" : "Female";
  13. }
  14. }
  15. @Component
  16. struct Information {
  17. @ObjectLink info: Info;
  18. @State index: number = 0;
  19. isRenderText(index: number) : number {
  20. console.info(`index ${index} is rendered`);
  21. return 1;
  22. }
  23. build() {
  24. Row() {
  25. Text("id: " + this.info.ids)
  26. .fontSize(20)
  27. .margin({
  28. left: 30,
  29. right: 5
  30. })
  31. Text("age: " + this.info.age)
  32. .fontSize(20)
  33. .margin({
  34. left: 5,
  35. right: 5
  36. })
  37. .position({x: 100})
  38. .opacity(this.isRenderText(this.index))
  39. .onClick(() => {
  40. this.info.age++;
  41. })
  42. Text("gender: " + this.info.gender)
  43. .margin({
  44. left: 5,
  45. right: 5
  46. })
  47. .position({x: 180})
  48. .fontSize(20)
  49. }
  50. }
  51. }
  52. @Entry
  53. @Component
  54. struct Page {
  55. @State infoList: InfoList = new InfoList();
  56. @State items: string[] = [];
  57. aboutToAppear() {
  58. this.items.push("Head");
  59. this.items.push("List");
  60. for (let i = 0; i < 20; i++) {
  61. this.infoList.push(new Info());
  62. }
  63. }
  64. build() {
  65. Row() {
  66. Column() {
  67. ForEach(this.items, (item: string) => {
  68. if (item == "Head") {
  69. Text("Personal Info")
  70. .fontSize(40)
  71. } else if (item == "List") {
  72. List() {
  73. ForEach(this.infoList, (info: Info, index) => {
  74. ListItem() {
  75. Information({
  76. // in low version, DevEco may throw a warning, but it does not matter.
  77. // you can still compile and run.
  78. info: info,
  79. index: index
  80. })
  81. }
  82. .margin({
  83. top: 5,
  84. bottom: 5
  85. })
  86. })
  87. }
  88. }
  89. })
  90. }
  91. }
  92. }
  93. }

上述代码的运行效果如下。GitCode - 全球开发者的开源社区,开源代码托管平台

properly-use-state-management-to-develope-2

修改后的代码使用对象数组代替了原有的多个属性数组,能够避免数组的“冗余刷新”的情况。这是因为对于数组来说,对象内的变化是无法感知的,数组只能观测数组项层级的变化,例如新增数据项,修改数据项(普通数组是直接修改数据项的值,在对象数组的场景下是整个对象被重新赋值,改变某个数据项对象中的属性不会被观测到)、删除数据项等。这意味着当改变对象内的某个属性时,对于数组来说,对象是没有变化的,也就不会去刷新。在当前状态管理的观测能力中,除了数组嵌套对象的场景外,对象嵌套对象的场景也是无法观测到变化的,这一部分内容将在将复杂对象拆分成多个小对象的集合中讲到。同时修改代码时使用了自定义组件与ForEach的结合,这一部分内容将在在ForEach中使用自定义组件搭配对象数组讲到。

将复杂大对象拆分成多个小对象的集合

说明:

从API version 11开始,推荐优先使用@Track装饰器解决该场景的问题。

在开发过程中,我们有时会定义一个大的对象,其中包含了很多样式相关的属性,并且在父子组件间传递这个对象,将其中的属性绑定在组件上。

  1. @Observed
  2. class UIStyle {
  3. translateX: number = 0;
  4. translateY: number = 0;
  5. scaleX: number = 0.3;
  6. scaleY: number = 0.3;
  7. width: number = 336;
  8. height: number = 178;
  9. posX: number = 10;
  10. posY: number = 50;
  11. alpha: number = 0.5;
  12. borderRadius: number = 24;
  13. imageWidth: number = 78;
  14. imageHeight: number = 78;
  15. translateImageX: number = 0;
  16. translateImageY: number = 0;
  17. fontSize: number = 20;
  18. }
  19. @Component
  20. struct SpecialImage {
  21. @ObjectLink uiStyle: UIStyle;
  22. private isRenderSpecialImage() : number { // function to show whether the component is rendered
  23. console.info("SpecialImage is rendered");
  24. return 1;
  25. }
  26. build() {
  27. Image($r('app.media.icon')) // 在API12及以后的工程中使用app.media.app_icon
  28. .width(this.uiStyle.imageWidth)
  29. .height(this.uiStyle.imageHeight)
  30. .margin({ top: 20 })
  31. .translate({
  32. x: this.uiStyle.translateImageX,
  33. y: this.uiStyle.translateImageY
  34. })
  35. .opacity(this.isRenderSpecialImage()) // if the Image is rendered, it will call the function
  36. }
  37. }
  38. @Component
  39. struct CompA {
  40. @ObjectLink uiStyle: UIStyle
  41. // the following functions are used to show whether the component is called to be rendered
  42. private isRenderColumn() : number {
  43. console.info("Column is rendered");
  44. return 1;
  45. }
  46. private isRenderStack() : number {
  47. console.info("Stack is rendered");
  48. return 1;
  49. }
  50. private isRenderImage() : number {
  51. console.info("Image is rendered");
  52. return 1;
  53. }
  54. private isRenderText() : number {
  55. console.info("Text is rendered");
  56. return 1;
  57. }
  58. build() {
  59. Column() {
  60. SpecialImage({
  61. // in low version, Dev Eco may throw a warning
  62. // But you can still build and run the code
  63. uiStyle: this.uiStyle
  64. })
  65. Stack() {
  66. Column() {
  67. Image($r('app.media.icon')) // 在API12及以后的工程中使用app.media.app_icon
  68. .opacity(this.uiStyle.alpha)
  69. .scale({
  70. x: this.uiStyle.scaleX,
  71. y: this.uiStyle.scaleY
  72. })
  73. .padding(this.isRenderImage())
  74. .width(300)
  75. .height(300)
  76. }
  77. .width('100%')
  78. .position({ y: -80 })
  79. Stack() {
  80. Text("Hello World")
  81. .fontColor("#182431")
  82. .fontWeight(FontWeight.Medium)
  83. .fontSize(this.uiStyle.fontSize)
  84. .opacity(this.isRenderText())
  85. .margin({ top: 12 })
  86. }
  87. .opacity(this.isRenderStack())
  88. .position({
  89. x: this.uiStyle.posX,
  90. y: this.uiStyle.posY
  91. })
  92. .width('100%')
  93. .height('100%')
  94. }
  95. .margin({ top: 50 })
  96. .borderRadius(this.uiStyle.borderRadius)
  97. .opacity(this.isRenderStack())
  98. .backgroundColor("#FFFFFF")
  99. .width(this.uiStyle.width)
  100. .height(this.uiStyle.height)
  101. .translate({
  102. x: this.uiStyle.translateX,
  103. y: this.uiStyle.translateY
  104. })
  105. Column() {
  106. Button("Move")
  107. .width(312)
  108. .fontSize(20)
  109. .backgroundColor("#FF007DFF")
  110. .margin({ bottom: 10 })
  111. .onClick(() => {
  112. animateTo({
  113. duration: 500
  114. },() => {
  115. this.uiStyle.translateY = (this.uiStyle.translateY + 180) % 250;
  116. })
  117. })
  118. Button("Scale")
  119. .borderRadius(20)
  120. .backgroundColor("#FF007DFF")
  121. .fontSize(20)
  122. .width(312)
  123. .onClick(() => {
  124. this.uiStyle.scaleX = (this.uiStyle.scaleX + 0.6) % 0.8;
  125. })
  126. }
  127. .position({
  128. y:666
  129. })
  130. .height('100%')
  131. .width('100%')
  132. }
  133. .opacity(this.isRenderColumn())
  134. .width('100%')
  135. .height('100%')
  136. }
  137. }
  138. @Entry
  139. @Component
  140. struct Page {
  141. @State uiStyle: UIStyle = new UIStyle();
  142. build() {
  143. Stack() {
  144. CompA({
  145. // in low version, Dev Eco may throw a warning
  146. // But you can still build and run the code
  147. uiStyle: this.uiStyle
  148. })
  149. }
  150. .backgroundColor("#F1F3F5")
  151. }
  152. }

上述代码的运行效果如下。GitCode - 全球开发者的开源社区,开源代码托管平台

properly-use-state-management-to-develope-3

优化前点击move按钮的脏节点更新耗时如下图:

img

在上面的示例中,UIStyle定义了多个属性,并且这些属性分别被多个组件关联。当点击任意一个按钮更改其中的某些属性时,会导致所有这些关联uiStyle的组件进行刷新,虽然它们其实并不需要进行刷新(因为组件的属性都没有改变)。通过定义的一系列isRender函数,可以观察到这些组件的刷新。当点击“move”按钮进行平移动画时,由于translateY的值的多次改变,会导致每一次都存在“冗余刷新”的问题,这对应用的性能有着很大的负面影响。

这是因为当前状态管理的一个刷新机制,假设定义了一个有20个属性的类,创建类的对象实例,将20个属性绑定到组件上,这时修改其中的某个属性,除了这个属性关联的组件会刷新之外,其他的19个属性关联的组件也都会刷新,即使这些属性本身并没有发生变化。

这个机制会导致在使用一个复杂大对象与多个组件关联时,刷新性能的下降。对此,推荐将一个复杂大对象拆分成多个小对象的集合,在保留原有代码结构的基础上,减少“冗余刷新”,实现精准控制组件的更新范围。

  1. @Observed
  2. class NeedRenderImage { // properties only used in the same component can be divided into the same new divided class
  3. public translateImageX: number = 0;
  4. public translateImageY: number = 0;
  5. public imageWidth:number = 78;
  6. public imageHeight:number = 78;
  7. }
  8. @Observed
  9. class NeedRenderScale { // properties usually used together can be divided into the same new divided class
  10. public scaleX: number = 0.3;
  11. public scaleY: number = 0.3;
  12. }
  13. @Observed
  14. class NeedRenderAlpha { // properties that may be used in different places can be divided into the same new divided class
  15. public alpha: number = 0.5;
  16. }
  17. @Observed
  18. class NeedRenderSize { // properties usually used together can be divided into the same new divided class
  19. public width: number = 336;
  20. public height: number = 178;
  21. }
  22. @Observed
  23. class NeedRenderPos { // properties usually used together can be divided into the same new divided class
  24. public posX: number = 10;
  25. public posY: number = 50;
  26. }
  27. @Observed
  28. class NeedRenderBorderRadius { // properties that may be used in different places can be divided into the same new divided class
  29. public borderRadius: number = 24;
  30. }
  31. @Observed
  32. class NeedRenderFontSize { // properties that may be used in different places can be divided into the same new divided class
  33. public fontSize: number = 20;
  34. }
  35. @Observed
  36. class NeedRenderTranslate { // properties usually used together can be divided into the same new divided class
  37. public translateX: number = 0;
  38. public translateY: number = 0;
  39. }
  40. @Observed
  41. class UIStyle {
  42. // define new variable instead of using old one
  43. needRenderTranslate: NeedRenderTranslate = new NeedRenderTranslate();
  44. needRenderFontSize: NeedRenderFontSize = new NeedRenderFontSize();
  45. needRenderBorderRadius: NeedRenderBorderRadius = new NeedRenderBorderRadius();
  46. needRenderPos: NeedRenderPos = new NeedRenderPos();
  47. needRenderSize: NeedRenderSize = new NeedRenderSize();
  48. needRenderAlpha: NeedRenderAlpha = new NeedRenderAlpha();
  49. needRenderScale: NeedRenderScale = new NeedRenderScale();
  50. needRenderImage: NeedRenderImage = new NeedRenderImage();
  51. }
  52. @Component
  53. struct SpecialImage {
  54. @ObjectLink uiStyle : UIStyle;
  55. @ObjectLink needRenderImage: NeedRenderImage // receive the new class from its parent component
  56. private isRenderSpecialImage() : number { // function to show whether the component is rendered
  57. console.info("SpecialImage is rendered");
  58. return 1;
  59. }
  60. build() {
  61. Image($r('app.media.icon')) // 在API12及以后的工程中使用app.media.app_icon
  62. .width(this.needRenderImage.imageWidth) // !! use this.needRenderImage.xxx rather than this.uiStyle.needRenderImage.xxx !!
  63. .height(this.needRenderImage.imageHeight)
  64. .margin({top:20})
  65. .translate({
  66. x: this.needRenderImage.translateImageX,
  67. y: this.needRenderImage.translateImageY
  68. })
  69. .opacity(this.isRenderSpecialImage()) // if the Image is rendered, it will call the function
  70. }
  71. }
  72. @Component
  73. struct CompA {
  74. @ObjectLink uiStyle: UIStyle;
  75. @ObjectLink needRenderTranslate: NeedRenderTranslate; // receive the new class from its parent component
  76. @ObjectLink needRenderFontSize: NeedRenderFontSize;
  77. @ObjectLink needRenderBorderRadius: NeedRenderBorderRadius;
  78. @ObjectLink needRenderPos: NeedRenderPos;
  79. @ObjectLink needRenderSize: NeedRenderSize;
  80. @ObjectLink needRenderAlpha: NeedRenderAlpha;
  81. @ObjectLink needRenderScale: NeedRenderScale;
  82. // the following functions are used to show whether the component is called to be rendered
  83. private isRenderColumn() : number {
  84. console.info("Column is rendered");
  85. return 1;
  86. }
  87. private isRenderStack() : number {
  88. console.info("Stack is rendered");
  89. return 1;
  90. }
  91. private isRenderImage() : number {
  92. console.info("Image is rendered");
  93. return 1;
  94. }
  95. private isRenderText() : number {
  96. console.info("Text is rendered");
  97. return 1;
  98. }
  99. build() {
  100. Column() {
  101. SpecialImage({
  102. // in low version, Dev Eco may throw a warning
  103. // But you can still build and run the code
  104. uiStyle: this.uiStyle,
  105. needRenderImage: this.uiStyle.needRenderImage //send it to its child
  106. })
  107. Stack() {
  108. Column() {
  109. Image($r('app.media.icon')) // 在API12及以后的工程中使用app.media.app_icon
  110. .opacity(this.needRenderAlpha.alpha)
  111. .scale({
  112. x: this.needRenderScale.scaleX, // use this.needRenderXxx.xxx rather than this.uiStyle.needRenderXxx.xxx
  113. y: this.needRenderScale.scaleY
  114. })
  115. .padding(this.isRenderImage())
  116. .width(300)
  117. .height(300)
  118. }
  119. .width('100%')
  120. .position({ y: -80 })
  121. Stack() {
  122. Text("Hello World")
  123. .fontColor("#182431")
  124. .fontWeight(FontWeight.Medium)
  125. .fontSize(this.needRenderFontSize.fontSize)
  126. .opacity(this.isRenderText())
  127. .margin({ top: 12 })
  128. }
  129. .opacity(this.isRenderStack())
  130. .position({
  131. x: this.needRenderPos.posX,
  132. y: this.needRenderPos.posY
  133. })
  134. .width('100%')
  135. .height('100%')
  136. }
  137. .margin({ top: 50 })
  138. .borderRadius(this.needRenderBorderRadius.borderRadius)
  139. .opacity(this.isRenderStack())
  140. .backgroundColor("#FFFFFF")
  141. .width(this.needRenderSize.width)
  142. .height(this.needRenderSize.height)
  143. .translate({
  144. x: this.needRenderTranslate.translateX,
  145. y: this.needRenderTranslate.translateY
  146. })
  147. Column() {
  148. Button("Move")
  149. .width(312)
  150. .fontSize(20)
  151. .backgroundColor("#FF007DFF")
  152. .margin({ bottom: 10 })
  153. .onClick(() => {
  154. animateTo({
  155. duration: 500
  156. }, () => {
  157. this.needRenderTranslate.translateY = (this.needRenderTranslate.translateY + 180) % 250;
  158. })
  159. })
  160. Button("Scale")
  161. .borderRadius(20)
  162. .backgroundColor("#FF007DFF")
  163. .fontSize(20)
  164. .width(312)
  165. .margin({ bottom: 10 })
  166. .onClick(() => {
  167. this.needRenderScale.scaleX = (this.needRenderScale.scaleX + 0.6) % 0.8;
  168. })
  169. Button("Change Image")
  170. .borderRadius(20)
  171. .backgroundColor("#FF007DFF")
  172. .fontSize(20)
  173. .width(312)
  174. .onClick(() => { // in the parent component, still use this.uiStyle.needRenderXxx.xxx to change the properties
  175. this.uiStyle.needRenderImage.imageWidth = (this.uiStyle.needRenderImage.imageWidth + 30) % 160;
  176. this.uiStyle.needRenderImage.imageHeight = (this.uiStyle.needRenderImage.imageHeight + 30) % 160;
  177. })
  178. }
  179. .position({
  180. y: 616
  181. })
  182. .height('100%')
  183. .width('100%')
  184. }
  185. .opacity(this.isRenderColumn())
  186. .width('100%')
  187. .height('100%')
  188. }
  189. }
  190. @Entry
  191. @Component
  192. struct Page {
  193. @State uiStyle: UIStyle = new UIStyle();
  194. build() {
  195. Stack() {
  196. CompA({
  197. // in low version, Dev Eco may throw a warning
  198. // But you can still build and run the code
  199. uiStyle: this.uiStyle,
  200. needRenderTranslate: this.uiStyle.needRenderTranslate, //send all the new class child need
  201. needRenderFontSize: this.uiStyle.needRenderFontSize,
  202. needRenderBorderRadius: this.uiStyle.needRenderBorderRadius,
  203. needRenderPos: this.uiStyle.needRenderPos,
  204. needRenderSize: this.uiStyle.needRenderSize,
  205. needRenderAlpha: this.uiStyle.needRenderAlpha,
  206. needRenderScale: this.uiStyle.needRenderScale
  207. })
  208. }
  209. .backgroundColor("#F1F3F5")
  210. }
  211. }

上述代码的运行效果如下。GitCode - 全球开发者的开源社区,开源代码托管平台

properly-use-state-management-to-develope-4

优化后点击move按钮的脏节点更新耗时如下图:

img

修改后的代码将原来的大类中的十五个属性拆成了八个小类,并且在绑定的组件上也做了相应的适配。属性拆分遵循以下几点原则:

  • 只作用在同一个组件上的多个属性可以被拆分进同一个新类,即示例中的NeedRenderImage。适用于组件经常被不关联的属性改变而引起刷新的场景,这个时候就要考虑拆分属性,或者重新考虑ViewModel设计是否合理。
  • 经常被同时使用的属性可以被拆分进同一个新类,即示例中的NeedRenderScale、NeedRenderTranslate、NeedRenderPos、NeedRenderSize。适用于属性经常成对出现,或者被作用在同一个样式上的情况,例如.translate、.position、.scale等(这些样式通常会接收一个对象作为参数)。
  • 可能被用在多个组件上或相对较独立的属性应该被单独拆分进一个新类,即示例中的NeedRenderAlpha,NeedRenderBorderRadius、NeedRenderFontSize。适用于一个属性作用在多个组件上或者与其他属性没有联系的情况,例如.opacity、.borderRadius等(这些样式通常相对独立)。

属性拆分的原理和属性合并类似,都是在嵌套场景下,状态管理无法观测二层以上的属性变化,所以不会因为二层的数据变化导致一层关联的其他属性被刷新,同时利用@Observed和@ObjectLink在父子节点间传递二层的对象,从而在子组件中正常的观测二层的数据变化,实现精准刷新。

使用@Track装饰器则无需做属性拆分,也能达到同样控制组件更新范围的作用。

  1. @Observed
  2. class UIStyle {
  3. @Track translateX: number = 0;
  4. @Track translateY: number = 0;
  5. @Track scaleX: number = 0.3;
  6. @Track scaleY: number = 0.3;
  7. @Track width: number = 336;
  8. @Track height: number = 178;
  9. @Track posX: number = 10;
  10. @Track posY: number = 50;
  11. @Track alpha: number = 0.5;
  12. @Track borderRadius: number = 24;
  13. @Track imageWidth: number = 78;
  14. @Track imageHeight: number = 78;
  15. @Track translateImageX: number = 0;
  16. @Track translateImageY: number = 0;
  17. @Track fontSize: number = 20;
  18. }
  19. @Component
  20. struct SpecialImage {
  21. @ObjectLink uiStyle: UIStyle;
  22. private isRenderSpecialImage() : number { // function to show whether the component is rendered
  23. console.info("SpecialImage is rendered");
  24. return 1;
  25. }
  26. build() {
  27. Image($r('app.media.icon')) // 在API12及以后的工程中使用app.media.app_icon
  28. .width(this.uiStyle.imageWidth)
  29. .height(this.uiStyle.imageHeight)
  30. .margin({ top: 20 })
  31. .translate({
  32. x: this.uiStyle.translateImageX,
  33. y: this.uiStyle.translateImageY
  34. })
  35. .opacity(this.isRenderSpecialImage()) // if the Image is rendered, it will call the function
  36. }
  37. }
  38. @Component
  39. struct CompA {
  40. @ObjectLink uiStyle: UIStyle
  41. // the following functions are used to show whether the component is called to be rendered
  42. private isRenderColumn() : number {
  43. console.info("Column is rendered");
  44. return 1;
  45. }
  46. private isRenderStack() : number {
  47. console.info("Stack is rendered");
  48. return 1;
  49. }
  50. private isRenderImage() : number {
  51. console.info("Image is rendered");
  52. return 1;
  53. }
  54. private isRenderText() : number {
  55. console.info("Text is rendered");
  56. return 1;
  57. }
  58. build() {
  59. Column() {
  60. SpecialImage({
  61. // in low version, Dev Eco may throw a warning
  62. // But you can still build and run the code
  63. uiStyle: this.uiStyle
  64. })
  65. Stack() {
  66. Column() {
  67. Image($r('app.media.icon')) // 在API12及以后的工程中使用app.media.app_icon
  68. .opacity(this.uiStyle.alpha)
  69. .scale({
  70. x: this.uiStyle.scaleX,
  71. y: this.uiStyle.scaleY
  72. })
  73. .padding(this.isRenderImage())
  74. .width(300)
  75. .height(300)
  76. }
  77. .width('100%')
  78. .position({ y: -80 })
  79. Stack() {
  80. Text("Hello World")
  81. .fontColor("#182431")
  82. .fontWeight(FontWeight.Medium)
  83. .fontSize(this.uiStyle.fontSize)
  84. .opacity(this.isRenderText())
  85. .margin({ top: 12 })
  86. }
  87. .opacity(this.isRenderStack())
  88. .position({
  89. x: this.uiStyle.posX,
  90. y: this.uiStyle.posY
  91. })
  92. .width('100%')
  93. .height('100%')
  94. }
  95. .margin({ top: 50 })
  96. .borderRadius(this.uiStyle.borderRadius)
  97. .opacity(this.isRenderStack())
  98. .backgroundColor("#FFFFFF")
  99. .width(this.uiStyle.width)
  100. .height(this.uiStyle.height)
  101. .translate({
  102. x: this.uiStyle.translateX,
  103. y: this.uiStyle.translateY
  104. })
  105. Column() {
  106. Button("Move")
  107. .width(312)
  108. .fontSize(20)
  109. .backgroundColor("#FF007DFF")
  110. .margin({ bottom: 10 })
  111. .onClick(() => {
  112. animateTo({
  113. duration: 500
  114. },() => {
  115. this.uiStyle.translateY = (this.uiStyle.translateY + 180) % 250;
  116. })
  117. })
  118. Button("Scale")
  119. .borderRadius(20)
  120. .backgroundColor("#FF007DFF")
  121. .fontSize(20)
  122. .width(312)
  123. .onClick(() => {
  124. this.uiStyle.scaleX = (this.uiStyle.scaleX + 0.6) % 0.8;
  125. })
  126. }
  127. .position({
  128. y:666
  129. })
  130. .height('100%')
  131. .width('100%')
  132. }
  133. .opacity(this.isRenderColumn())
  134. .width('100%')
  135. .height('100%')
  136. }
  137. }
  138. @Entry
  139. @Component
  140. struct Page {
  141. @State uiStyle: UIStyle = new UIStyle();
  142. build() {
  143. Stack() {
  144. CompA({
  145. // in low version, Dev Eco may throw a warning
  146. // But you can still build and run the code
  147. uiStyle: this.uiStyle
  148. })
  149. }
  150. .backgroundColor("#F1F3F5")
  151. }
  152. }

使用@Observed装饰或被声明为状态变量的类对象绑定组件

在开发过程中,会有“重置数据”的场景,将一个新创建的对象赋值给原有的状态变量,实现数据的刷新。如果不注意新创建对象的类型,可能会出现UI不刷新的现象。

  1. @Observed
  2. class Child {
  3. count: number;
  4. constructor(count: number) {
  5. this.count = count
  6. }
  7. }
  8. @Observed
  9. class ChildList extends Array<Child> {
  10. };
  11. @Observed
  12. class Ancestor {
  13. childList: ChildList;
  14. constructor(childList: ChildList) {
  15. this.childList = childList;
  16. }
  17. public loadData() {
  18. let tempList = [new Child(1), new Child(2), new Child(3), new Child(4), new Child(5)];
  19. this.childList = tempList;
  20. }
  21. public clearData() {
  22. this.childList = []
  23. }
  24. }
  25. @Component
  26. struct CompChild {
  27. @Link childList: ChildList;
  28. @ObjectLink child: Child;
  29. build() {
  30. Row() {
  31. Text(this.child.count+'')
  32. .height(70)
  33. .fontSize(20)
  34. .borderRadius({
  35. topLeft: 6,
  36. topRight: 6
  37. })
  38. .margin({left: 50})
  39. Button('X')
  40. .backgroundColor(Color.Red)
  41. .onClick(()=>{
  42. let index = this.childList.findIndex((item) => {
  43. return item.count === this.child.count
  44. })
  45. if (index !== -1) {
  46. this.childList.splice(index, 1);
  47. }
  48. })
  49. .margin({
  50. left: 200,
  51. right:30
  52. })
  53. }
  54. .margin({
  55. top:15,
  56. left: 15,
  57. right:10,
  58. bottom:15
  59. })
  60. .borderRadius(6)
  61. .backgroundColor(Color.Grey)
  62. }
  63. }
  64. @Component
  65. struct CompList {
  66. @ObjectLink@Watch('changeChildList') childList: ChildList;
  67. changeChildList() {
  68. console.info('CompList ChildList change');
  69. }
  70. isRenderCompChild(index: number) : number {
  71. console.info("Comp Child is render" + index);
  72. return 1;
  73. }
  74. build() {
  75. Column() {
  76. List() {
  77. ForEach(this.childList, (item: Child, index) => {
  78. ListItem() {
  79. // in low version, Dev Eco may throw a warning
  80. // But you can still build and run the code
  81. CompChild({
  82. childList: this.childList,
  83. child: item
  84. })
  85. .opacity(this.isRenderCompChild(index))
  86. }
  87. })
  88. }
  89. .height('70%')
  90. }
  91. }
  92. }
  93. @Component
  94. struct CompAncestor {
  95. @ObjectLink ancestor: Ancestor;
  96. build() {
  97. Column() {
  98. // in low version, Dev Eco may throw a warning
  99. // But you can still build and run the code
  100. CompList({ childList: this.ancestor.childList })
  101. Row() {
  102. Button("Clear")
  103. .onClick(() => {
  104. this.ancestor.clearData()
  105. })
  106. .width(100)
  107. .margin({right: 50})
  108. Button("Recover")
  109. .onClick(() => {
  110. this.ancestor.loadData()
  111. })
  112. .width(100)
  113. }
  114. }
  115. }
  116. }
  117. @Entry
  118. @Component
  119. struct Page {
  120. @State childList: ChildList = [new Child(1), new Child(2), new Child(3), new Child(4),new Child(5)];
  121. @State ancestor: Ancestor = new Ancestor(this.childList)
  122. build() {
  123. Column() {
  124. // in low version, Dev Eco may throw a warning
  125. // But you can still build and run the code
  126. CompAncestor({ ancestor: this.ancestor})
  127. }
  128. }
  129. }

上述代码运行效果如下。GitCode - 全球开发者的开源社区,开源代码托管平台

properly-use-state-management-to-develope-5

上述代码维护了一个ChildList类型的数据源,点击"X"按钮删除一些数据后再点击Recover进行恢复ChildList,发现再次点击"X"按钮进行删除时,UI并没有刷新,同时也没有打印出“CompList ChildList change”的日志。

代码中对数据源childList重新赋值时,是通过Ancestor对象的方法loadData。

  1. public loadData() {
  2. let tempList = [new Child(1), new Child(2), new Child(3), new Child(4), new Child(5)];
  3. this.childList = tempList;
  4. }

在loadData方法中,创建了一个临时的Child类型的数组tempList,并且将Ancestor对象的成员变量的childList指向了tempList。但是这里创建的Child[]类型的数组tempList其实并没有能被观测的能力(也就说它的变化无法主动触发UI刷新)。当它被赋值给childList之后,触发了ForEach的刷新,使得界面完成了重建,但是再次点击删除时,由于此时的childList已经指向了新的tempList代表的数组,并且这个数组并没有被观测的能力,是个静态的量,所以它的更改不会被观测到,也就不会引起UI的刷新。实际上这个时候childList里的数据已经减少了,只是UI没有刷新。

有些开发者会注意到,在Page中初始化定义childList的时候,也是以这样一种方法去进行初始化的。

  1. @State childList: ChildList = [new Child(1), new Child(2), new Child(3), new Child(4),new Child(5)];
  2. @State ancestor: Ancestor = new Ancestor(this.childList)

但是由于这里的childList实际上是被@State装饰了,根据当前状态管理的观测能力,尽管右边赋值的是一个Child[]类型的数据,它并没有被@Observed装饰,这里的childList却依然具备了被观测的能力,所以能够正常的触发UI的刷新。当去掉childList的@State的装饰器后,不去重置数据源,也无法通过点击“X”按钮触发刷新。

因此,需要将具有观测能力的类对象绑定组件,来确保当改变这些类对象的内容时,UI能够正常的刷新。

  1. @Observed
  2. class Child {
  3. count: number;
  4. constructor(count: number) {
  5. this.count = count
  6. }
  7. }
  8. @Observed
  9. class ChildList extends Array<Child> {
  10. };
  11. @Observed
  12. class Ancestor {
  13. childList: ChildList;
  14. constructor(childList: ChildList) {
  15. this.childList = childList;
  16. }
  17. public loadData() {
  18. let tempList = new ChildList();
  19. for (let i = 1; i < 6; i ++) {
  20. tempList.push(new Child(i));
  21. }
  22. this.childList = tempList;
  23. }
  24. public clearData() {
  25. this.childList = []
  26. }
  27. }
  28. @Component
  29. struct CompChild {
  30. @Link childList: ChildList;
  31. @ObjectLink child: Child;
  32. build() {
  33. Row() {
  34. Text(this.child.count+'')
  35. .height(70)
  36. .fontSize(20)
  37. .borderRadius({
  38. topLeft: 6,
  39. topRight: 6
  40. })
  41. .margin({left: 50})
  42. Button('X')
  43. .backgroundColor(Color.Red)
  44. .onClick(()=>{
  45. let index = this.childList.findIndex((item) => {
  46. return item.count === this.child.count
  47. })
  48. if (index !== -1) {
  49. this.childList.splice(index, 1);
  50. }
  51. })
  52. .margin({
  53. left: 200,
  54. right:30
  55. })
  56. }
  57. .margin({
  58. top:15,
  59. left: 15,
  60. right:10,
  61. bottom:15
  62. })
  63. .borderRadius(6)
  64. .backgroundColor(Color.Grey)
  65. }
  66. }
  67. @Component
  68. struct CompList {
  69. @ObjectLink@Watch('changeChildList') childList: ChildList;
  70. changeChildList() {
  71. console.info('CompList ChildList change');
  72. }
  73. isRenderCompChild(index: number) : number {
  74. console.info("Comp Child is render" + index);
  75. return 1;
  76. }
  77. build() {
  78. Column() {
  79. List() {
  80. ForEach(this.childList, (item: Child, index) => {
  81. ListItem() {
  82. // in low version, Dev Eco may throw a warning
  83. // But you can still build and run the code
  84. CompChild({
  85. childList: this.childList,
  86. child: item
  87. })
  88. .opacity(this.isRenderCompChild(index))
  89. }
  90. })
  91. }
  92. .height('70%')
  93. }
  94. }
  95. }
  96. @Component
  97. struct CompAncestor {
  98. @ObjectLink ancestor: Ancestor;
  99. build() {
  100. Column() {
  101. // in low version, Dev Eco may throw a warning
  102. // But you can still build and run the code
  103. CompList({ childList: this.ancestor.childList })
  104. Row() {
  105. Button("Clear")
  106. .onClick(() => {
  107. this.ancestor.clearData()
  108. })
  109. .width(100)
  110. .margin({right: 50})
  111. Button("Recover")
  112. .onClick(() => {
  113. this.ancestor.loadData()
  114. })
  115. .width(100)
  116. }
  117. }
  118. }
  119. }
  120. @Entry
  121. @Component
  122. struct Page {
  123. @State childList: ChildList = [new Child(1), new Child(2), new Child(3), new Child(4),new Child(5)];
  124. @State ancestor: Ancestor = new Ancestor(this.childList)
  125. build() {
  126. Column() {
  127. // in low version, Dev Eco may throw a warning
  128. // But you can still build and run the code
  129. CompAncestor({ ancestor: this.ancestor})
  130. }
  131. }
  132. }

上述代码运行效果如下。

properly-use-state-management-to-develope-6

核心的修改点是将原本Child[]类型的tempList修改为具有被观测能力的ChildList类。

  1. public loadData() {
  2. let tempList = new ChildList();
  3. for (let i = 1; i < 6; i ++) {
  4. tempList.push(new Child(i));
  5. }
  6. this.childList = tempList;
  7. }

ChildList类型在定义的时候使用了@Observed进行装饰,所以用new创建的对象tempList具有被观测的能力,因此在点击“X”按钮删除其中一条内容时,变量childList就能够观测到变化,所以触发了ForEach的刷新,最终UI渲染刷新。

合理使用ForEach/LazyForEach

减少使用LazyForEach的重建机制刷新UI

开发过程中通常会将LazyForEach和状态变量结合起来使用。

  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: StringData[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): StringData {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. notifyDataMove(from: number, to: number): void {
  44. this.listeners.forEach(listener => {
  45. listener.onDataMove(from, to);
  46. })
  47. }
  48. }
  49. class MyDataSource extends BasicDataSource {
  50. private dataArray: StringData[] = [];
  51. public totalCount(): number {
  52. return this.dataArray.length;
  53. }
  54. public getData(index: number): StringData {
  55. return this.dataArray[index];
  56. }
  57. public addData(index: number, data: StringData): void {
  58. this.dataArray.splice(index, 0, data);
  59. this.notifyDataAdd(index);
  60. }
  61. public pushData(data: StringData): void {
  62. this.dataArray.push(data);
  63. this.notifyDataAdd(this.dataArray.length - 1);
  64. }
  65. public reloadData(): void {
  66. this.notifyDataReload();
  67. }
  68. }
  69. class StringData {
  70. message: string;
  71. imgSrc: Resource;
  72. constructor(message: string, imgSrc: Resource) {
  73. this.message = message;
  74. this.imgSrc = imgSrc;
  75. }
  76. }
  77. @Entry
  78. @Component
  79. struct MyComponent {
  80. private data: MyDataSource = new MyDataSource();
  81. aboutToAppear() {
  82. for (let i = 0; i <= 9; i++) {
  83. this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); // 在API12及以后的工程中使用app.media.app_icon
  84. }
  85. }
  86. build() {
  87. List({ space: 3 }) {
  88. LazyForEach(this.data, (item: StringData, index: number) => {
  89. ListItem() {
  90. Column() {
  91. Text(item.message).fontSize(20)
  92. .onAppear(() => {
  93. console.info("text appear:" + item.message);
  94. })
  95. Image(item.imgSrc)
  96. .width(100)
  97. .height(100)
  98. .onAppear(() => {
  99. console.info("image appear");
  100. })
  101. }.margin({ left: 10, right: 10 })
  102. }
  103. .onClick(() => {
  104. item.message += '0';
  105. this.data.reloadData();
  106. })
  107. }, (item: StringData, index: number) => JSON.stringify(item))
  108. }.cachedCount(5)
  109. }
  110. }

上述代码运行效果如下。GitCode - 全球开发者的开源社区,开源代码托管平台

properly-use-state-management-to-develope-7

可以观察到在点击更改message之后,图片“闪烁”了一下,同时输出了组件的onAppear日志,这说明组件进行了重建。这是因为在更改message之后,导致LazyForEach中这一项的key值发生了变化,使得LazyForEach在reloadData的时候将这一项ListItem进行了重建。Text组件仅仅更改显示的内容却发生了重建,而不是更新。而尽管Image组件没有需要重新绘制的内容,但是因为触发LazyForEach的重建,会使得同样位于ListItem下的Image组件重新创建。

当前LazyForEach与状态变量都能触发UI的刷新,两者的性能开销是不一样的。使用LazyForEach刷新会对组件进行重建,如果包含了多个组件,则会产生比较大的性能开销。使用状态变量刷新会对组件进行刷新,具体到状态变量关联的组件上,相对于LazyForEach的重建来说,范围更小更精确。因此,推荐使用状态变量来触发LazyForEach中的组件刷新,这就需要使用自定义组件。

  1. class BasicDataSource implements IDataSource {
  2. private listeners: DataChangeListener[] = [];
  3. private originDataArray: StringData[] = [];
  4. public totalCount(): number {
  5. return 0;
  6. }
  7. public getData(index: number): StringData {
  8. return this.originDataArray[index];
  9. }
  10. registerDataChangeListener(listener: DataChangeListener): void {
  11. if (this.listeners.indexOf(listener) < 0) {
  12. console.info('add listener');
  13. this.listeners.push(listener);
  14. }
  15. }
  16. unregisterDataChangeListener(listener: DataChangeListener): void {
  17. const pos = this.listeners.indexOf(listener);
  18. if (pos >= 0) {
  19. console.info('remove listener');
  20. this.listeners.splice(pos, 1);
  21. }
  22. }
  23. notifyDataReload(): void {
  24. this.listeners.forEach(listener => {
  25. listener.onDataReloaded();
  26. })
  27. }
  28. notifyDataAdd(index: number): void {
  29. this.listeners.forEach(listener => {
  30. listener.onDataAdd(index);
  31. })
  32. }
  33. notifyDataChange(index: number): void {
  34. this.listeners.forEach(listener => {
  35. listener.onDataChange(index);
  36. })
  37. }
  38. notifyDataDelete(index: number): void {
  39. this.listeners.forEach(listener => {
  40. listener.onDataDelete(index);
  41. })
  42. }
  43. notifyDataMove(from: number, to: number): void {
  44. this.listeners.forEach(listener => {
  45. listener.onDataMove(from, to);
  46. })
  47. }
  48. }
  49. class MyDataSource extends BasicDataSource {
  50. private dataArray: StringData[] = [];
  51. public totalCount(): number {
  52. return this.dataArray.length;
  53. }
  54. public getData(index: number): StringData {
  55. return this.dataArray[index];
  56. }
  57. public addData(index: number, data: StringData): void {
  58. this.dataArray.splice(index, 0, data);
  59. this.notifyDataAdd(index);
  60. }
  61. public pushData(data: StringData): void {
  62. this.dataArray.push(data);
  63. this.notifyDataAdd(this.dataArray.length - 1);
  64. }
  65. }
  66. @Observed
  67. class StringData {
  68. @Track message: string;
  69. @Track imgSrc: Resource;
  70. constructor(message: string, imgSrc: Resource) {
  71. this.message = message;
  72. this.imgSrc = imgSrc;
  73. }
  74. }
  75. @Entry
  76. @Component
  77. struct MyComponent {
  78. @State data: MyDataSource = new MyDataSource();
  79. aboutToAppear() {
  80. for (let i = 0; i <= 9; i++) {
  81. this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); // 在API12及以后的工程中使用app.media.app_icon
  82. }
  83. }
  84. build() {
  85. List({ space: 3 }) {
  86. LazyForEach(this.data, (item: StringData, index: number) => {
  87. ListItem() {
  88. // in low version, Dev Eco may throw a warning
  89. // But you can still build and run the code
  90. ChildComponent({data: item})
  91. }
  92. .onClick(() => {
  93. item.message += '0';
  94. })
  95. }, (item: StringData, index: number) => index.toString())
  96. }.cachedCount(5)
  97. }
  98. }
  99. @Component
  100. struct ChildComponent {
  101. @ObjectLink data: StringData
  102. build() {
  103. Column() {
  104. Text(this.data.message).fontSize(20)
  105. .onAppear(() => {
  106. console.info("text appear:" + this.data.message)
  107. })
  108. Image(this.data.imgSrc)
  109. .width(100)
  110. .height(100)
  111. }.margin({ left: 10, right: 10 })
  112. }
  113. }

上述代码运行效果如下。

properly-use-state-management-to-develope-8

可以观察到UI能够正常刷新,图片没有“闪烁”,且没有输出日志信息,说明没有对Text组件和Image组件进行重建。

这是因为使用自定义组件之后,可以通过@Observed和@ObjectLink配合去直接更改自定义组件内的状态变量实现刷新,而不需要利用LazyForEach进行重建。使用@Track装饰器分别装饰StringData类型中的message和imgSrc属性可以使更新范围进一步缩小到指定的Text组件。

在ForEach中使用自定义组件搭配对象数组

开发过程中经常会使用对象数组和ForEach结合起来使用,但是写法不当的话会出现UI不刷新的情况。

  1. @Observed
  2. class StyleList extends Array<TextStyle> {
  3. };
  4. @Observed
  5. class TextStyle {
  6. fontSize: number;
  7. constructor(fontSize: number) {
  8. this.fontSize = fontSize;
  9. }
  10. }
  11. @Entry
  12. @Component
  13. struct Page {
  14. @State styleList: StyleList = new StyleList();
  15. aboutToAppear() {
  16. for (let i = 15; i < 50; i++)
  17. this.styleList.push(new TextStyle(i));
  18. }
  19. build() {
  20. Column() {
  21. Text("Font Size List")
  22. .fontSize(50)
  23. .onClick(() => {
  24. for (let i = 0; i < this.styleList.length; i++) {
  25. this.styleList[i].fontSize++;
  26. }
  27. console.info("change font size");
  28. })
  29. List() {
  30. ForEach(this.styleList, (item: TextStyle) => {
  31. ListItem() {
  32. Text("Hello World")
  33. .fontSize(item.fontSize)
  34. }
  35. })
  36. }
  37. }
  38. }
  39. }

上述代码运行效果如下。

properly-use-state-management-to-develope-9

由于ForEach中生成的item是一个常量,因此当点击改变item中的内容时,没有办法观测到UI刷新,尽管日志表面item中的值已经改变了(这体现在打印了“change font size”的日志)。因此,需要使用自定义组件,配合@ObjectLink来实现观测的能力。

  1. @Observed
  2. class StyleList extends Array<TextStyle> {
  3. };
  4. @Observed
  5. class TextStyle {
  6. fontSize: number;
  7. constructor(fontSize: number) {
  8. this.fontSize = fontSize;
  9. }
  10. }
  11. @Component
  12. struct TextComponent {
  13. @ObjectLink textStyle: TextStyle;
  14. build() {
  15. Text("Hello World")
  16. .fontSize(this.textStyle.fontSize)
  17. }
  18. }
  19. @Entry
  20. @Component
  21. struct Page {
  22. @State styleList: StyleList = new StyleList();
  23. aboutToAppear() {
  24. for (let i = 15; i < 50; i++)
  25. this.styleList.push(new TextStyle(i));
  26. }
  27. build() {
  28. Column() {
  29. Text("Font Size List")
  30. .fontSize(50)
  31. .onClick(() => {
  32. for (let i = 0; i < this.styleList.length; i++) {
  33. this.styleList[i].fontSize++;
  34. }
  35. console.info("change font size");
  36. })
  37. List() {
  38. ForEach(this.styleList, (item: TextStyle) => {
  39. ListItem() {
  40. // in low version, Dev Eco may throw a warning
  41. // But you can still build and run the code
  42. TextComponent({ textStyle: item})
  43. }
  44. })
  45. }
  46. }
  47. }
  48. }

上述代码的运行效果如下。

properly-use-state-management-to-develope-10

使用@ObjectLink接受传入的item后,使得TextComponent组件内的textStyle变量具有了被观测的能力。在父组件更改styleList中的值时,由于@ObjectLink是引用传递,所以会观测到styleList每一个数据项的地址指向的对应item的fontSize的值被改变,因此触发UI的刷新。

这是一个较为实用的使用状态管理进行刷新的开发方式。

文章知识点与官方知识档案匹配,可进一步学习相关知识
CS入门技能树Linux入门初识Linux42834 人正在系统学习中
鸿蒙NEXT全套学习资料
微信名片
注:本文转载自blog.csdn.net的让开,我要吃人了的文章"https://blog.csdn.net/weixin_55362248/article/details/141864987"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top