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

以上是个人经验分享

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

相关推荐
Huang兄4 小时前
鸿蒙-List和Grid拖拽排序:仿微信小程序删除效果
harmonyos·arkts·arkui
anyup1 天前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
Ranger09291 天前
鸿蒙开发新范式:Gpui
rust·harmonyos
Huang兄1 天前
鸿蒙-深色模式适配
harmonyos·arkts·arkui
SummerKaze3 天前
为鸿蒙开发者写一个 nvm:hmvm 的设计与实现
harmonyos
在人间耕耘5 天前
HarmonyOS Vision Kit 视觉AI实战:把官方 Demo 改造成一套能长期复用的组件库
人工智能·深度学习·harmonyos
王码码20355 天前
Flutter for OpenHarmony:socket_io_client 实时通信的事实标准(Node.js 后端的最佳拍档) 深度解析与鸿蒙适配指南
android·flutter·ui·华为·node.js·harmonyos
HarmonyOS_SDK5 天前
【FAQ】HarmonyOS SDK 闭源开放能力 — Ads Kit
harmonyos
Swift社区5 天前
如何利用 ArkUI 框架优化鸿蒙应用的渲染性能
华为·harmonyos
特立独行的猫a5 天前
uni-app x跨平台开发实战:开发鸿蒙HarmonyOS影视票房榜组件完整实现过程
华为·uni-app·harmonyos·轮播图·uniapp-x