首页 最新 热门 推荐

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

HarmonyOS开发实战( Beta5版)精准控制组件的更新实践规范

  • 25-03-03 08:41
  • 2909
  • 11412
blog.csdn.net

在复杂页面开发的场景下,精准控制组件更新的范围对提高应用运行性能尤为重要。

多组件关联同一对象的不同属性

在学习本示例之前,需要了解当前状态管理的刷新机制。

  1. @Observed
  2. class ClassA {
  3. prop1: number = 0;
  4. prop2: string = "This is Prop2";
  5. }
  6. @Component
  7. struct CompA {
  8. @ObjectLink a: ClassA;
  9. private sizeFont: number = 30; // the private variable does not invoke rendering
  10. private isRenderText() : number {
  11. this.sizeFont++; // the change of sizeFont will not invoke rendering, but showing that the function is called
  12. console.info("Text prop2 is rendered");
  13. return this.sizeFont;
  14. }
  15. build() {
  16. Column() {
  17. Text(this.a.prop2) // when this.a.prop2 changes, it will invoke Text rerendering
  18. .fontSize(this.isRenderText()) //if the Text renders, the function isRenderText will be called
  19. }
  20. }
  21. }
  22. @Entry
  23. @Component
  24. struct Page {
  25. @State a: ClassA = new ClassA();
  26. build() {
  27. Row() {
  28. Column() {
  29. Text("Prop1: " + this.a.prop1)
  30. .fontSize(50)
  31. .margin({ bottom: 20 })
  32. CompA({a: this.a})
  33. Button("Change prop1")
  34. .width(200)
  35. .margin({ top: 20 })
  36. .onClick(() => {
  37. this.a.prop1 = this.a.prop1 + 1 ;
  38. })
  39. }
  40. .width('100%')
  41. }
  42. .width('100%')
  43. .height('100%')
  44. }
  45. }

在上面的示例中,当点击按钮改变prop1的值时,尽管CompA中的组件并没有使用prop1,但是仍然可以观测到关联prop2的Text组件进行了刷新,这体现在Text组件的字体变大,同时控制台输出了“Text prop2 is rendered”的日志上。这说明当改变了一个由@Observed装饰的类的实例对象中的某个属性时(即上面示例中的prop1),会导致所有关联这个对象中某个属性的组件一起刷新,尽管这些组件可能并没有直接使用到该改变的属性(即上面示例中使用prop的Text组件)。这样就会导致一些隐形的“冗余刷新”,当涉及到“冗余刷新”的组件数量很多时,就会大大影响组件的刷新性能。

上文代码运行图示如下:GitCode - 全球开发者的开源社区,开源代码托管平台

precisely-control-render-scope-01.gif

下面的示例代码为一个较典型的冗余刷新场景。

  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'))
  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. // when you compile this code in API9, IDE may tell you that
  61. // "Assigning the '@ObjectLink' decorated attribute 'uiStyle' to the '@ObjectLink' decorated attribute 'uiStyle' is not allowed. "
  62. // But you can still run the code by Previewer
  63. SpecialImage({
  64. uiStyle: this.uiStyle
  65. })
  66. Stack() {
  67. Column() {
  68. Image($r('app.media.icon'))
  69. .opacity(this.uiStyle.alpha)
  70. .scale({
  71. x: this.uiStyle.scaleX,
  72. y: this.uiStyle.scaleY
  73. })
  74. .padding(this.isRenderImage())
  75. .width(300)
  76. .height(300)
  77. }
  78. .width('100%')
  79. .position({ y: -80 })
  80. Stack() {
  81. Text("Hello World")
  82. .fontColor("#182431")
  83. .fontWeight(FontWeight.Medium)
  84. .fontSize(this.uiStyle.fontSize)
  85. .opacity(this.isRenderText())
  86. .margin({ top: 12 })
  87. }
  88. .opacity(this.isRenderStack())
  89. .position({
  90. x: this.uiStyle.posX,
  91. y: this.uiStyle.posY
  92. })
  93. .width('100%')
  94. .height('100%')
  95. }
  96. .margin({ top: 50 })
  97. .borderRadius(this.uiStyle.borderRadius)
  98. .opacity(this.isRenderStack())
  99. .backgroundColor("#FFFFFF")
  100. .width(this.uiStyle.width)
  101. .height(this.uiStyle.height)
  102. .translate({
  103. x: this.uiStyle.translateX,
  104. y: this.uiStyle.translateY
  105. })
  106. Column() {
  107. Button("Move")
  108. .width(312)
  109. .fontSize(20)
  110. .backgroundColor("#FF007DFF")
  111. .margin({ bottom: 10 })
  112. .onClick(() => {
  113. animateTo({
  114. duration: 500
  115. },() => {
  116. this.uiStyle.translateY = (this.uiStyle.translateY + 180) % 250;
  117. })
  118. })
  119. Button("Scale")
  120. .borderRadius(20)
  121. .backgroundColor("#FF007DFF")
  122. .fontSize(20)
  123. .width(312)
  124. .onClick(() => {
  125. this.uiStyle.scaleX = (this.uiStyle.scaleX + 0.6) % 0.8;
  126. })
  127. }
  128. .position({
  129. y:666
  130. })
  131. .height('100%')
  132. .width('100%')
  133. }
  134. .opacity(this.isRenderColumn())
  135. .width('100%')
  136. .height('100%')
  137. }
  138. }
  139. @Entry
  140. @Component
  141. struct Page {
  142. @State uiStyle: UIStyle = new UIStyle();
  143. build() {
  144. Stack() {
  145. CompA({
  146. uiStyle: this.uiStyle
  147. })
  148. }
  149. .backgroundColor("#F1F3F5")
  150. }
  151. }

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

上文代码运行图示如下:

precisely-control-render-scope-02.gif

对此,推荐将属性进行拆分,将一个大的属性对象拆分成几个小的属性对象,来减少甚至避免冗余刷新的现象,达到精准控制组件的更新范围。

为了达成这一目的,首先需要了解当前属性更新观测的另一个机制。

下面为示例代码。GitCode - 全球开发者的开源社区,开源代码托管平台

  1. @Observed
  2. class ClassB {
  3. subProp1: number = 100;
  4. }
  5. @Observed
  6. class ClassA {
  7. prop1: number = 0;
  8. prop2: string = "This is Prop2";
  9. prop3: ClassB = new ClassB();
  10. }
  11. @Component
  12. struct CompA {
  13. @ObjectLink a: ClassA;
  14. private sizeFont: number = 30; // the private variable does not invoke rendering
  15. private isRenderText() : number {
  16. this.sizeFont++; // the change of sizeFont will not invoke rendering, but showing that the function is called
  17. console.info("Text prop2 is rendered");
  18. return this.sizeFont;
  19. }
  20. build() {
  21. Column() {
  22. Text(this.a.prop2) // when this.a.prop1 changes, it will invoke Text rerendering
  23. .margin({ bottom: 10 })
  24. .fontSize(this.isRenderText()) //if the Text renders, the function isRenderText will be called
  25. Text("subProp1 : " + this.a.prop3.subProp1) //the Text can not observe the change of subProp1
  26. .fontSize(30)
  27. }
  28. }
  29. }
  30. @Entry
  31. @Component
  32. struct Page {
  33. @State a: ClassA = new ClassA();
  34. build() {
  35. Row() {
  36. Column() {
  37. Text("Prop1: " + this.a.prop1)
  38. .margin({ bottom: 20 })
  39. .fontSize(50)
  40. CompA({a: this.a})
  41. Button("Change prop1")
  42. .width(200)
  43. .fontSize(20)
  44. .backgroundColor("#FF007DFF")
  45. .margin({
  46. top: 10,
  47. bottom: 10
  48. })
  49. .onClick(() => {
  50. this.a.prop1 = this.a.prop1 + 1 ;
  51. })
  52. Button("Change subProp1")
  53. .width(200)
  54. .fontSize(20)
  55. .backgroundColor("#FF007DFF")
  56. .onClick(() => {
  57. this.a.prop3.subProp1 = this.a.prop3.subProp1 + 1;
  58. })
  59. }
  60. .width('100%')
  61. }
  62. .width('100%')
  63. .height('100%')
  64. }
  65. }

在上面的示例中,当点击按钮“Change subProp1”时,可以发现页面并没有进行刷新,这是因为对subProp1的更改并没有被组件观测到。当再次点击“Change prop1”时,可以发现页面进行了刷新,同时显示了prop1与subProp1的最新值。依据ArkUI状态管理机制,状态变量自身只能观察到第一层的变化,所以对于“Change subProp1",对第二层的属性赋值,是无法观察到的,即对this.a.prop3.subProp1的变化并不会引起组件的刷新,即使subProp1的值其实已经产生了变化。而对this.a.prop1的改变则会引起刷新。

上文代码运行图示如下:

precisely-control-render-scope-03.gif

利用这一个机制,可以做到精准控制组件的更新范围。

  1. @Observed
  2. class ClassB {
  3. subProp1: number = 100;
  4. }
  5. @Observed
  6. class ClassA {
  7. prop1: number = 0;
  8. prop2: string = "This is Prop2";
  9. prop3: ClassB = new ClassB();
  10. }
  11. @Component
  12. struct CompA {
  13. @ObjectLink a: ClassA;
  14. @ObjectLink b: ClassB; // a new objectlink variable
  15. private sizeFont: number = 30;
  16. private isRenderText() : number {
  17. this.sizeFont++;
  18. console.info("Text prop2 is rendered");
  19. return this.sizeFont;
  20. }
  21. private isRenderTextSubProp1() : number {
  22. this.sizeFont++;
  23. console.info("Text subProp1 is rendered");
  24. return this.sizeFont;
  25. }
  26. build() {
  27. Column() {
  28. Text(this.a.prop2) // when this.a.prop1 changes, it will invoke Text rerendering
  29. .margin({ bottom: 10 })
  30. .fontSize(this.isRenderText()) //if the Text renders, the function isRenderText will be called
  31. Text("subProp1 : " + this.b.subProp1) // use directly b rather than a.prop3
  32. .fontSize(30)
  33. .opacity(this.isRenderTextSubProp1())
  34. }
  35. }
  36. }
  37. @Entry
  38. @Component
  39. struct Page {
  40. @State a: ClassA = new ClassA();
  41. build() {
  42. Row() {
  43. Column() {
  44. Text("Prop1: " + this.a.prop1)
  45. .margin({ bottom: 20 })
  46. .fontSize(50)
  47. CompA({
  48. a: this.a,
  49. b: this.a.prop3
  50. })
  51. Button("Change prop1")
  52. .width(200)
  53. .fontSize(20)
  54. .backgroundColor("#FF007DFF")
  55. .margin({
  56. top: 10,
  57. bottom: 10
  58. })
  59. .onClick(() => {
  60. this.a.prop1 = this.a.prop1 + 1 ;
  61. })
  62. Button("Change subProp1")
  63. .width(200)
  64. .fontSize(20)
  65. .backgroundColor("#FF007DFF")
  66. .margin({
  67. top: 10,
  68. bottom: 10
  69. })
  70. .onClick(() => {
  71. this.a.prop3.subProp1 = this.a.prop3.subProp1 + 1;
  72. })
  73. }
  74. .width('100%')
  75. }
  76. .width('100%')
  77. .height('100%')
  78. }
  79. }

在上面的示例中,在CompA中定义了一个新的ObjectLink装饰的变量b,并由Page创建CompA时,将a对象中的prop3传入给b,这样就能在子组件CompA中直接使用b,这使得组件实际上和b进行了关联,组件也就能观测到b中的subProp1的变化,当点击按钮“Change subProp1”的时时候,可以只触发相关联的Text的组件的刷新,而不会引起其他的组件刷新(因为其他组件关联的是a),同样的其他对于a中属性的修改也不会导致该Text组件的刷新。

上文代码运行图示如下:

precisely-control-render-scope-04.gif

通过这个方法,可以将上文的复杂冗余刷新场景进行属性拆分实现性能优化。

  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'))
  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. // when you compile this code in API9, IDE may tell you that
  102. // "Assigning the '@ObjectLink' decorated attribute 'uiStyle' to the '@ObjectLink' decorated attribute 'uiStyle' is not allowed. "
  103. // "Assigning the '@ObjectLink' decorated attribute 'uiStyle' to the '@ObjectLink' decorated attribute 'needRenderImage' is not allowed. "
  104. // But you can still run the code by Previewer
  105. SpecialImage({
  106. uiStyle: this.uiStyle,
  107. needRenderImage: this.uiStyle.needRenderImage //send it to its child
  108. })
  109. Stack() {
  110. Column() {
  111. Image($r('app.media.icon'))
  112. .opacity(this.needRenderAlpha.alpha)
  113. .scale({
  114. x: this.needRenderScale.scaleX, // use this.needRenderXxx.xxx rather than this.uiStyle.needRenderXxx.xxx
  115. y: this.needRenderScale.scaleY
  116. })
  117. .padding(this.isRenderImage())
  118. .width(300)
  119. .height(300)
  120. }
  121. .width('100%')
  122. .position({ y: -80 })
  123. Stack() {
  124. Text("Hello World")
  125. .fontColor("#182431")
  126. .fontWeight(FontWeight.Medium)
  127. .fontSize(this.needRenderFontSize.fontSize)
  128. .opacity(this.isRenderText())
  129. .margin({ top: 12 })
  130. }
  131. .opacity(this.isRenderStack())
  132. .position({
  133. x: this.needRenderPos.posX,
  134. y: this.needRenderPos.posY
  135. })
  136. .width('100%')
  137. .height('100%')
  138. }
  139. .margin({ top: 50 })
  140. .borderRadius(this.needRenderBorderRadius.borderRadius)
  141. .opacity(this.isRenderStack())
  142. .backgroundColor("#FFFFFF")
  143. .width(this.needRenderSize.width)
  144. .height(this.needRenderSize.height)
  145. .translate({
  146. x: this.needRenderTranslate.translateX,
  147. y: this.needRenderTranslate.translateY
  148. })
  149. Column() {
  150. Button("Move")
  151. .width(312)
  152. .fontSize(20)
  153. .backgroundColor("#FF007DFF")
  154. .margin({ bottom: 10 })
  155. .onClick(() => {
  156. animateTo({
  157. duration: 500
  158. }, () => {
  159. this.needRenderTranslate.translateY = (this.needRenderTranslate.translateY + 180) % 250;
  160. })
  161. })
  162. Button("Scale")
  163. .borderRadius(20)
  164. .backgroundColor("#FF007DFF")
  165. .fontSize(20)
  166. .width(312)
  167. .margin({ bottom: 10 })
  168. .onClick(() => {
  169. this.needRenderScale.scaleX = (this.needRenderScale.scaleX + 0.6) % 0.8;
  170. })
  171. Button("Change Image")
  172. .borderRadius(20)
  173. .backgroundColor("#FF007DFF")
  174. .fontSize(20)
  175. .width(312)
  176. .onClick(() => { // in the parent component, still use this.uiStyle.needRenderXxx.xxx to change the properties
  177. this.uiStyle.needRenderImage.imageWidth = (this.uiStyle.needRenderImage.imageWidth + 30) % 160;
  178. this.uiStyle.needRenderImage.imageHeight = (this.uiStyle.needRenderImage.imageHeight + 30) % 160;
  179. })
  180. }
  181. .position({
  182. y: 616
  183. })
  184. .height('100%')
  185. .width('100%')
  186. }
  187. .opacity(this.isRenderColumn())
  188. .width('100%')
  189. .height('100%')
  190. }
  191. }
  192. @Entry
  193. @Component
  194. struct Page {
  195. @State uiStyle: UIStyle = new UIStyle();
  196. build() {
  197. Stack() {
  198. CompA({
  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. }

上文代码运行图示如下:

precisely-control-render-scope-05.gif

可以使用SmartPerf Host工具分别抓取优化前后点击“move”按钮时的trace数据,来查看属性拆分的性能收益。

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

precisely-control-render-scope-dirty-node-trace-01

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

precisely-control-render-scope-dirty-node-trace-02

从上面trace图中的“H:FlushDirtyNodeUpdate”标签可以看出,优化前点击“move”按钮的脏节点更新耗时为1ms388μs,而通过拆分属性进行优化后耗时仅828μs,性能提升了大约40.34%。

在上面的示例中将原先大类中的十五个属性拆成了八个小类,并且在组件的属性绑定中也进行了相应的适配。属性拆分遵循以下几点原则:

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

在对属性进行拆分后,对所有使用属性对组件进行绑定的时候,需要使用以下格式:

  1. .property(this.needRenderXxx.xxx)
  2. // sample
  3. Text("some text")
  4. .width(this.needRenderSize.width)
  5. .height(this.needRenderSize.height)
  6. .opacity(this.needRenderAlpha.alpha)

在父组件改变属性的值时,可以通过外层的父类去修改,即:

  1. // in parent Component
  2. this.parent.needRenderXxx.xxx = x;
  3. //example
  4. this.uiStyle.needRenderImage.imageWidth = (this.uiStyle.needRenderImage.imageWidth + 20) % 60;

在子组件本身改变属性的值时,推荐直接通过新类去修改,即:

  1. // in child Component
  2. this.needRenderXxx.xxx = x;
  3. //example
  4. this.needRenderScale.scaleX = (this.needRenderScale.scaleX + 0.6) % 1

属性拆分应当重点考虑变化较为频繁的属性,来提高应用运行的性能。

如果想要在父组件中使用拆分后的属性,推荐新定义一个@State修饰的状态变量配合使用。

  1. @Observed
  2. class NeedRenderProperty {
  3. public property: number = 1;
  4. };
  5. @Observed
  6. class SomeClass {
  7. needRenderProperty: NeedRenderProperty = new NeedRenderProperty();
  8. }
  9. @Entry
  10. @Component
  11. struct Page {
  12. @State someClass: SomeClass = new SomeClass();
  13. @State needRenderProperty: NeedRenderProperty = this.someClass.needRenderProperty
  14. build() {
  15. Row() {
  16. Column() {
  17. Text("property value: " + this.needRenderProperty.property)
  18. .fontSize(30)
  19. .margin({ bottom: 20 })
  20. Button("Change property")
  21. .onClick(() => {
  22. this.needRenderProperty.property++;
  23. })
  24. }
  25. .width('100%')
  26. }
  27. .width('100%')
  28. .height('100%')
  29. }
  30. }

多组件关联同一数据的条件刷新

多个组件依赖对象中的不同属性时,直接关联该对象会出现改变任一属性所有组件都刷新的现象,可以通过将类中的属性拆分组合成新类的方式精准控制组件刷新。

在多个组件依赖同一个数据源并根据数据源变化刷新组件的情况下,直接关联数据源会导致每次数据源改变都刷新所有组件。为精准控制组件刷新,可以采取以下策略:

  1. 使用 @Watch 装饰器:在组件中使用@Watch装饰器监听数据源,当数据变化时执行业务逻辑,确保只有满足条件的组件进行刷新。
  2. 事件驱动更新:对于复杂组件关系或跨层级情况,使用Emitter自定义事件发布订阅机制。数据源变化时触发相应事件,订阅该事件的组件接收到通知后,根据变化的具体值判断组件是否刷新。

【反例】

在下面的示例代码中,多个组件直接关联同一个数据源,但是未使用@Watch装饰器和Emitter事件驱动更新,导致了冗余的组件刷新。

  1. @Entry
  2. @Component
  3. struct Index {
  4. @State currentIndex: number = 0; // 当前选中的列表项下标
  5. private listData: string[] = [];
  6. aboutToAppear(): void {
  7. for (let i = 0; i < 10; i++) {
  8. this.listData.push(`组件 ${i}`);
  9. }
  10. }
  11. build() {
  12. Row() {
  13. Column() {
  14. List() {
  15. ForEach(this.listData, (item: string, index: number) => {
  16. ListItem() {
  17. ListItemComponent({ item: item, index: index, currentIndex: this.currentIndex })
  18. }
  19. })
  20. }
  21. .alignListItem(ListItemAlign.Center)
  22. }
  23. .width('100%')
  24. }
  25. .height('100%')
  26. }
  27. }
  28. @Component
  29. struct ListItemComponent {
  30. @Prop item: string;
  31. @Prop index: number; // 列表项的下标
  32. @Link currentIndex: number;
  33. private sizeFont: number = 50;
  34. isRender(): number {
  35. console.info(`ListItemComponent ${this.index} Text is rendered`);
  36. return this.sizeFont;
  37. }
  38. build() {
  39. Column() {
  40. Text(this.item)
  41. .fontSize(this.isRender())
  42. // 根据当前列表项下标index与currentIndex的差值来动态设置文本的颜色
  43. .fontColor(Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue)
  44. .onClick(() => {
  45. this.currentIndex = this.index;
  46. })
  47. }
  48. }
  49. }

上述示例中,每个ListItemComponent组件点击Text后会将当前点击的列表项下标index赋值给currentIndex,@Link装饰的状态变量currentIndex会将变化传递给父组件Index和所有ListItemComponent组件。然后,在所有ListItemComponent组件中,根据列表项下标index与currentIndex的差值的绝对值是否小于等于1来决定Text的颜色,如果满足条件,则文本显示为红色,否则显示为蓝色。

下面是运行效果图。 

redundant_refresh

可以看到每次点击后即使其中部分Text组件的颜色并没有发生改变,所有的Text组件也都会刷新。这是由于ListItemComponent组件中的Text组件直接关联了currentIndex,而不是根据currentIndex计算得到的颜色。

针对上述父子组件层级关系的场景,推荐使用状态装饰器@Watch监听数据源。当数据源改变时,在@Watch的监听回调中执行业务逻辑。组件关联回调的处理结果,而不是直接关联数据源。

【正例】

下面是对上述示例的优化,展示如何通过@Watch装饰器实现精准刷新。

  1. @Entry
  2. @Component
  3. struct Index {
  4. @State currentIndex: number = 0; // 当前选中的列表项下标
  5. private listData: string[] = [];
  6. aboutToAppear(): void {
  7. for (let i = 0; i < 10; i++) {
  8. this.listData.push(`组件 ${i}`);
  9. }
  10. }
  11. build() {
  12. Row() {
  13. Column() {
  14. List() {
  15. ForEach(this.listData, (item: string, index: number) => {
  16. ListItem() {
  17. ListItemComponent({ item: item, index: index, currentIndex: this.currentIndex })
  18. }
  19. })
  20. }
  21. .alignListItem(ListItemAlign.Center)
  22. }
  23. .width('100%')
  24. }
  25. .height('100%')
  26. }
  27. }
  28. @Component
  29. struct ListItemComponent {
  30. @Prop item: string;
  31. @Prop index: number; // 列表项的下标
  32. @Link @Watch('onCurrentIndexUpdate') currentIndex: number;
  33. @State color: Color = Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue;
  34. isRender(): number {
  35. console.info(`ListItemComponent ${this.index} Text is rendered`);
  36. return 50;
  37. }
  38. onCurrentIndexUpdate() {
  39. // 根据当前列表项下标index与currentIndex的差值来动态修改color的值
  40. this.color = Math.abs(this.index - this.currentIndex) <= 1 ? Color.Red : Color.Blue;
  41. }
  42. build() {
  43. Column() {
  44. Text(this.item)
  45. .fontSize(this.isRender())
  46. .fontColor(this.color)
  47. .onClick(() => {
  48. this.currentIndex = this.index;
  49. })
  50. }
  51. }
  52. }

上述代码中,ListItemComponent组件中的状态变量currentIndex使用@Watch装饰,Text组件直接关联新的状态变量color。当currentIndex发生变化时,会触发onCurrentIndexUpdate方法,在其中将表达式的运算结果赋值给状态变量color。只有color的值发生变化时,Text组件才会重新渲染。

运行效果图如下。

precise_refresh.gif

【效果对比】

使用SmartPerf Host工具分别抓取正反例中切换选中项的trace数据,通过点击组件2的脏节点更新耗时分析二者的性能差异。

反例点击组件2的脏节点更新耗时如下图:

precisely-control-render-scope-dirty-node-trace-03

正例点击组件2的脏节点更新耗时如下图:

precisely-control-render-scope-dirty-node-trace-04

从上面的trace图可以看出,反例中点击组件2后十个ListItemComponent组件节点都触发了更新,脏节点更新耗时3ms308μs,而正例只有三个节点触发更新,脏节点更新耗时仅为969μs,性能提升了大约70.7%。

被依赖的数据源仅在父子或兄弟关系的组件中传递时,可以参考上述示例,使用@State/@Link/@Watch装饰器进行状态管理,实现组件的精准刷新。

当组件关系层级较多但都归属于同一个确定的组件树时,推荐使用@Provide/@Consume传递数据,使用@Watch装饰器监听数据变化,在监听回调中执行业务逻辑。参考如下伪代码。

  1. // in ParentComponent
  2. @Provide @Watch('onCurrentValueUpdate') currentValue: number = 0;
  3. @State parentComponentResult: number = 0;
  4. onCurrentValueUpdate() {
  5. // 执行业务逻辑
  6. this.parentComponentResult = X; // X 代表基于业务逻辑需要赋给parentComponentResult的值
  7. }
  8. Component.property(this.parentComponentResult)
  9. // in ChildComponent
  10. @Provide @Watch('onCurrentValueUpdate') currentValue: number = 0;
  11. @State childComponentResult: number = 0;
  12. onCurrentValueUpdate() {
  13. // 执行业务逻辑
  14. this.childComponentResult = X; // X 代表基于业务逻辑需要赋给childComponentResult的值
  15. }
  16. Component.property(this.childComponentResult)
  17. // in NestedComponent
  18. @Provide @Watch('onCurrentValueUpdate') currentValue: number = 0;
  19. @State nestedComponentResult: number = 0;
  20. onCurrentValueUpdate() {
  21. // 执行业务逻辑
  22. this.nestedComponentResult = X; // X 代表基于业务逻辑需要赋给nestedComponentResult的值
  23. }
  24. Component.property(this.nestedComponentResult)

当组件关系复杂或跨越层级过多时,推荐使用 Emitter 自定义事件发布订阅的方式。当数据源改变时发布事件,依赖该数据源的组件通过订阅事件来获取数据源的改变,完成业务逻辑的处理,从而实现组件的精准刷新。

下面通过部分示例代码介绍使用方式。

ButtonComponent组件作为交互组件触发数据变更,ListItemComponent组件接收数据做相应的UI刷新。

  1. Column() {
  2. Row() {
  3. Column() {
  4. ButtonComponent()
  5. }
  6. }
  7. Column() {
  8. Column() {
  9. List() {
  10. ForEach(this.listData, (item: string, index: number) => {
  11. ListItemComponent({ myItem: item, index: index })
  12. })
  13. }
  14. .alignListItem(ListItemAlign.Center)
  15. }
  16. }
  17. }

由于ButtonComponent组件和ListItemComponent组件的组件关系较为复杂,因此在ButtonComponent组件中的Button回调中,可以使用emitter.emit发送事件,在ListItemComponent组件中订阅事件。在事件触发的回调中接收数据value,通过业务逻辑决定是否修改状态变量color,从而实现精准控制ListItemComponent组件中Text的刷新。

  1. // in ButtonComponent
  2. Button(`下标是${this.value}的倍数的组件文字变为红色`)
  3. .onClick(() => {
  4. let event: emitter.InnerEvent = {
  5. eventId: 1,
  6. priority: emitter.EventPriority.LOW
  7. };
  8. let eventData: emitter.EventData = {
  9. data: {
  10. value: this.value
  11. }
  12. };
  13. // 发送eventId为1的事件,事件内容为eventData
  14. emitter.emit(event, eventData);
  15. this.value++;
  16. })
  1. // in ListItemComponent
  2. @State color: Color = Color.Black;
  3. aboutToAppear(): void {
  4. let event: emitter.InnerEvent = {
  5. eventId: 1
  6. };
  7. // 收到eventId为1的事件后执行该回调
  8. let callback = (eventData: emitter.EventData): void => {
  9. if (eventData.data?.value !== 0 && this.index % eventData.data?.value === 0) {
  10. this.color = Color.Red;
  11. }
  12. };
  13. // 订阅eventId为1的事件
  14. emitter.on(event, callback);
  15. }
  16. build() {
  17. Column() {
  18. Text(this.myItem)
  19. .fontSize(this.isRender())
  20. .fontColor(this.color)
  21. }
  22. }

最后

小编在之前的鸿蒙系统扫盲中,有很多朋友给我留言,不同的角度的问了一些问题,我明显感觉到一点,那就是许多人参与鸿蒙开发,但是又不知道从哪里下手,因为资料太多,太杂,教授的人也多,无从选择。有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)文档用来跟着学习是非常有必要的。 

为了确保高效学习,建议规划清晰的学习路线,涵盖以下关键阶段:

GitCode - 全球开发者的开源社区,开源代码托管平台  希望这一份鸿蒙学习文档能够给大家带来帮助~


鸿蒙(HarmonyOS NEXT)最新学习路线

​

该路线图包含基础技能、就业必备技能、多媒体技术、六大电商APP、进阶高级技能、实战就业级设备开发,不仅补充了华为官网未涉及的解决方案

路线图适合人群:

IT开发人员:想要拓展职业边界
零基础小白:鸿蒙爱好者,希望从0到1学习,增加一项技能。
技术提升/进阶跳槽:发展瓶颈期,提升职场竞争力,快速掌握鸿蒙技术

2.视频学习教程+学习PDF文档

HarmonyOS Next 最新全套视频教程

  纯血版鸿蒙全套学习文档(面试、文档、全套视频等)       

​​

总结

参与鸿蒙开发,你要先认清适合你的方向,如果是想从事鸿蒙应用开发方向的话,可以参考本文的学习路径,简单来说就是:为了确保高效学习,建议规划清晰的学习路线

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

/ 登录

评论记录:

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

分类栏目

后端 (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