鸿蒙:使用@Reusable实现组件的复用,提升性能

1、前言

之前开发中,没有使用过@Reusable实现组件的复用,因为自己也不咋涉及高性能损耗。这次在看文档时发现了这个装饰器,实测发现可以避免组件的重复创建,所以在列表子组件比较多,并且频繁销毁重建的情况下适合使用该装饰器。

2、参考文档

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-reusablehttps://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-reusable

3、核心思路

1. 创建一个用来渲染列表的数组

2. 列表的每项调用使用@Reusable装饰的组件

4、核心代码

复制代码
@Reusable
@Component
struct myComponent {
  @Prop item: number = 0

  aboutToAppear(): void {
    console.log("组件创建了" + this.item)
  }

  aboutToReuse(): void {
    // 如果使用了@Reusable,那么不会重新创建,而是会复用
    console.log("组件复用了" + this.item)
  }

  build() {
    Text("这是 " + this.item)
      .fontSize(20)
      .width("100%")
      .textAlign(TextAlign.Center)
  }
}

5、运行效果

6、完整代码

Index.ets

复制代码
@Entry
@Component
struct Index {
  @State arrayNum: Array<number> = []

  aboutToAppear(): void {
    this.pushArray()
  }

  pushArray() {
    this.arrayNum = []
    for (let index = 0; index < 10; index++) {
      this.arrayNum.push(index)

    }
  }

  build() {
    Column() {

      Row({ space: 20 }) {
        Button("清空列表")
          .onClick(() => {
            this.arrayNum = []
          })
        Button("创建列表")
          .onClick(() => {
            this.pushArray()
          })
      }

      List() {
        ForEach(this.arrayNum, (item: number) => {
          ListItem() {
            myComponent({ item: item })
          }
        })
      }
      .width("100%")
      .height("90%")
    }
  }
}

@Reusable
@Component
struct myComponent {
  @Prop item: number = 0

  aboutToAppear(): void {
    console.log("组件创建了" + this.item)
  }

  aboutToReuse(): void {
    // 如果使用了@Reusable,那么不会重新创建,而是会复用
    console.log("组件复用了" + this.item)
  }

  build() {
    Text("这是 " + this.item)
      .fontSize(20)
      .width("100%")
      .textAlign(TextAlign.Center)
  }
}

以上是个人经验分享

觉得有帮助可以点赞或收藏

相关推荐
爱笑的眼睛112 小时前
深入理解ArkTS装饰器:提升HarmonyOS应用开发效率
华为·harmonyos
Damon小智7 小时前
HarmonyOS 5 开发实践:分布式任务调度与设备协同架构
分布式·架构·harmonyos
superior tigre8 小时前
(huawei)最小栈
c++·华为·面试
●VON11 小时前
双非大学生自学鸿蒙5.0零基础入门到项目实战 -《基础篇》
android·华为·harmonyos·鸿蒙
Damon小智21 小时前
鸿蒙分布式数据服务(DDS)原理与企业同步实战
分布式·华为·harmonyos
猫林老师1 天前
HarmonyOS自动化测试与持续集成实战指南
ci/cd·华为·harmonyos
寂然如故1 天前
拥抱未来:HarmonyOS NEXT 开发新范式深度解析
华为·harmonyos
国霄1 天前
(2)Kotlin/Js For Harmony——如何复用ViewModel
harmonyos
星释1 天前
鸿蒙Flutter三方库适配指南:08.联合插件开发
flutter·华为·harmonyos
爱笑的眼睛111 天前
HarmonyOS WaterFlow瀑布流布局深度解析:从原理到性能优化
华为·harmonyos