鸿蒙:使用@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)
  }
}

以上是个人经验分享

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

相关推荐
key_3_feng30 分钟前
HarmonyOS 6.0 健康食谱应用开发方案
华为·harmonyos
麒麟ZHAO42 分钟前
鸿蒙flutter第三方库适配 - 文件对比工具
数据库·redis·flutter·华为·harmonyos
互联网散修43 分钟前
零基础鸿蒙应用开发第三十四节:MVVM架构下的商品管理登录页
架构·harmonyos·mvvm·登录
弓.长.1 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-svg(CAPI) — 矢量图形组件
react native·react.js·harmonyos
不爱吃糖的程序媛1 小时前
鸿蒙三方库适配HPKCHECK 文件执行流程详解
华为·harmonyos
见山是山-见水是水2 小时前
Flutter 框架跨平台鸿蒙开发 - 电子发票智能管理
flutter·华为·harmonyos
HarmonyOS_SDK2 小时前
化繁为简:顺丰速运App如何通过 HarmonyOS SDK实现专业级空间测量
harmonyos
不爱吃糖的程序媛2 小时前
鸿蒙三方库适配读懂 `HPKBUILD`:lycium 怎么知道「下载谁、怎么编、装到哪」?
服务器·华为·harmonyos
李游Leo3 小时前
别让压图拖垮首帧:系统 Picker + TaskPool + ImagePacker,把 HarmonyOS 图片整理链路做顺
harmonyos
2401_839633913 小时前
鸿蒙flutter第三方库适配 - 存储空间分析
flutter·华为·harmonyos