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

以上是个人经验分享

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

相关推荐
AI备忘录5 小时前
(十九)华为华三锐捷迈普思科 交换机链路聚合配置命令(LACP/静态聚合五厂商对照)
运维·服务器·网络·网络协议·tcp/ip·华为
贾伟康6 小时前
【时光清单|19】HarmonyOS ArkTS 回归测试实战:覆盖启动、空数据、异常输入和重复点击
软件测试·harmonyos·arkts·回归测试·hypium
坚果的博客6 小时前
Flutter OHOS 环境搭建实战:oh-3.44.9-dev 从 0 到 1 完整记录
flutter·华为·harmonyos
坚果的博客6 小时前
认识 CPF-RN:React Native 鸿蒙官方社区与四大核心仓库
react native·react.js·harmonyos
大雷神7 小时前
HarmonyOS ArkGraphics 2D可变帧率实操——同屏对比30、60和90 FPS动画
华为·harmonyos
OH_TPC7 小时前
【鸿蒙优选三方库】@react-native-ohos/react-native-fast-image:高性能图片加载与缓存组件
缓存·华为·harmonyos·鸿蒙
贾伟康9 小时前
【句匠|03】HarmonyOS ArkTS 每日打卡实战:实现连续天数、补签边界和本地日期判断
harmonyos·arkts·本地存储·每日打卡·学习应用
小雨青年9 小时前
【HarmonyOS 7 平行视界深度实战】02 从普通页面到第一个平行视界 Demo
华为·harmonyos
~远在太平洋~9 小时前
06-鸿蒙系统 uitest UI 自动化指南
ui·自动化·harmonyos
OH_TPC9 小时前
OpenHarmony平台RN三方库适配情况
华为·harmonyos·鸿蒙