HarmonyOS(35) @State使用注意事项

@State使用注意事项

注意事项

HarmonyOS鸿蒙学习笔记(5)@State作用说明和简单案例一文中简单介绍了@State的使用方法,但是@State装饰器使用有一些注意事项:在应用开发中,应避免在循环逻辑中频繁读取状态变量,而是应该放在循环外面读取。

反例

java 复制代码
@Entry
@Component
struct Index {
  @State message: string = '';

  build() {
    Column() {
      Button('点击打印日志')
        .onClick(() => {
          for (let i = 0; i < 10; i++) {
            //循环体中使用message
            hilog.info(0x0000, 'TAG', '%{public}s', this.message);
          }
        })
        .width('90%')
        .backgroundColor(Color.Blue)
        .fontColor(Color.White)
        .margin({
          top: 10
        })
    }
    .justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Center)
    .margin({
      top: 15
    })
  }
}

正例

java 复制代码
@Entry
@Component
struct Index {
  @State message: string = '';

  build() {
    Column() {
      Button('点击打印日志')
        .onClick(() => {
          //循环体外提前访问message变量
          let logMessage: string = this.message;
          for (let i = 0; i < 10; i++) {
            hilog.info(0x0000, 'TAG', '%{public}s', logMessage);
          }
        })
        .width('90%')
        .backgroundColor(Color.Blue)
        .fontColor(Color.White)
        .margin({
          top: 10
        })
    }
    .justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Center)
    .margin({
      top: 15
    })
  }
}

参考资料

状态管理优秀实践

相关推荐
Swift社区6 小时前
AI 原生鸿蒙应用开发实战
人工智能·华为·harmonyos
盐焗西兰花6 小时前
鸿蒙学习实战之路-Share Kit系列(12/17)-判断应用是否被系统分享拉起
前端·学习·harmonyos
互联网散修6 小时前
鸿蒙应用开发UI基础第二十四节:构造Preferences用户首选项数据存储开源工具
开源·harmonyos·鸿蒙应用开发教程
国医中兴8 小时前
Flutter 三方库 ngrouter 鸿蒙适配指南 - 实现高性能扁平化路由导航管理实战
flutter·harmonyos·鸿蒙·openharmony
大雷神9 小时前
HarmonyOS APP<玩转React>开源教程十:组件化开发概述
前端·react.js·开源·harmonyos
国医中兴9 小时前
Flutter 三方库 inject_generator 的鸿蒙化适配指南 - 自动化依赖注入注入生成器、驱动鸿蒙大型工程解耦实战
flutter·harmonyos·鸿蒙·openharmony·inject_generator
Easonmax9 小时前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-pager-view — 流畅的页面滑动体验
react native·react.js·harmonyos
讯方洋哥10 小时前
HarmonyOS App开发——鸿蒙ArkTS在手机和PC多终端适配机制应用
harmonyos
国医中兴10 小时前
Flutter 三方库 themed_color_palette 的鸿蒙化适配指南 - 定义语义化调色板、在鸿蒙端实现像素级的主题切换实战
flutter·harmonyos·鸿蒙·openharmony·themed_color_palette