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

以上是个人经验分享

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

相关推荐
陈_杨13 分钟前
前端成功转鸿蒙开发者真实案例,教大家如何开发鸿蒙APP--ArkTS 卡片开发完全指南
前端·harmonyos
陈_杨20 分钟前
前端成功转鸿蒙开发者真实案例,教大家如何开发鸿蒙APP--ArkTS 卡片刷新机制
前端·harmonyos
哈__39 分钟前
从入门小白到精通,玩转 React Native 鸿蒙跨平台开发:TouchableOpacity 触摸反馈组件
react native·react.js·harmonyos
小雨下雨的雨1 小时前
Flutter 框架跨平台鸿蒙开发 —— Flex 控件之响应式弹性布局
flutter·ui·华为·harmonyos·鸿蒙系统
哈__1 小时前
入门小白到精通,玩转 React Native 鸿蒙跨平台开发:Button 按钮组件与点击事件
react native·react.js·harmonyos
奋斗的小青年!!1 小时前
OpenHarmony Flutter实战:打造高性能订单确认流程步骤条
flutter·harmonyos·鸿蒙
Georgewu1 小时前
【HarmonyOS应用开发】鸿蒙碰一碰分享开发源码和流程讲解
harmonyos
行者962 小时前
Flutter跨平台骨架屏组件在鸿蒙系统上的实践与优化
flutter·harmonyos·鸿蒙
奋斗的小青年!!2 小时前
Flutter自定义图表跨平台适配OpenHarmony
flutter·harmonyos·鸿蒙
奋斗的小青年!!2 小时前
Flutter + OpenHarmony:高性能搜索组件深度优化实战解析
flutter·harmonyos·鸿蒙