鸿蒙状态

组件状态

  • @State 修饰的变量,会根据值改变更新UI,如果是嵌套属性的赋值改变不会变更;

  • @Prop修饰的变量只会在当前组件生效,不会同步回其父组件,不能在@Entry修饰的自定义组件中使用;

  • @Link 修饰的变量与其父组件中对应的数据双向绑定,不能再@Entry修饰的自定义组件中使用;
    通俗一点就是@Link修饰的变量,传递的参数有修改,不管在那取出来都是一样的,@Prop就相当于隔离,只能在自己的区域修改变更。

  • @Provide与@Consume,@Provide类似是一种全局模式,@Consume是对其的监听,一旦@Provide变更会全局同步,是一对多模式;

  • @Observed和@ObjectLink 嵌套类修饰,解决二次嵌套。@Observed修饰类,@ObjectLink引用;

应用状态

LocalStorage 页面级UI状态存储

  • @LocalStorageProp 单向绑定
    -@LocalStorageLink 双向绑定
//创建 LocalStorage, textParamA为key 值是10
var storage = new LocalStorage({ "textParamA": 10 })

@Component
struct LocalChild {
  @LocalStorageLink('textParamA') childLink: number = 1
  @LocalStorageProp('textParamA') propChild: number = 1

  build() {
    Column() {
      Button(`子布局 storage ${this.childLink}`)
        .onClick(() => {
          this.childLink += 3
        })

      Button(`子布局 单向 + 4  值= ${this.propChild}`)
        .onClick(() => {
          this.propChild += 4
        })
        .margin({ top: 10 })
    }.backgroundColor(Color.Red)
  }
}

@Entry(storage) //绑定LocalStorage
@Component
struct LocalStoragePage {
  @LocalStorageLink('textParamA') currentLink: number = 100

  build() {
    Column({ space: 18 }) {
      Button('父控件 storage=' + this.currentLink)
        .margin({ top: 50, left: 10 })
        .onClick(() => {
          this.currentLink += 3
        })
      LocalChild()

      Button("重置 storage")
        .margin({top:20})
        .onClick(()=>{
          storage.set<number>('textParamA',200)
        })
    }
  }
}

多个页面使用需要在UIAbility中配置

import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';

let record:Record<string,number> = {'wholeParam':1001}
let localStorage = new LocalStorage(record)
export default class EntryAbility extends UIAbility {

   storage:LocalStorage = localStorage

  onWindowStageCreate(windowStage: window.WindowStage) {
  //传递storage
    windowStage.loadContent('pages/Index',this.storage, (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

}

页面获取

import router from '@ohos.router'

let storage = LocalStorage.GetShared()

@Entry(storage)
@Component
struct Index {
  @State message: string = 'Hello World'

  @LocalStorageLink('wholeParam') wholeParam :number = 0

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
        Button(){
          Text('跳转')
            .fontSize(25)
            .fontWeight(FontWeight.Bold)
        }.type(ButtonType.Capsule)
        .margin({top: 20})
        .padding({left:20,right:20,top:5,bottom:5})
        .onClick(()=>{
          router.pushUrl({url:'pages/LocalStoragePage'}).then(()=>{
            console.info("跳转成功")
          }).catch((err)=>{
            console.info("跳转失败")
          })
        })

        Text('全局参数 = '+this.wholeParam).fontSize(16)
      }
      .width('100%')
    }
    .height('100%')
  }
}

AppStorage应用全局UI状态存储

在应用启动的时候会被创建成单例,对应的@StorageLink 和@StorageProp与Local的类似

PersistentStorage 持久化存储

需与AppStorage搭配是使用,UI和业务逻辑不直接访问PersistentStorage中的属性,所有的访问都是对AppStorage的访问,AppStorage中的更改会自动同步

  • 从AppStorage中访问PersistentStorage初始化属性
//初始化
PersistentStorage.PersistProp('persistentParam',100);
  1. 在AppStorage中获取对应属性
AppStorage.Get('persistentParam')  //100
//在组件中获取
@StorageLink('persistentParam)  param :number = 1;

Environment:设备环境查询

所有属性都是不可变的

// 将设备的语言code存入AppStorage,默认值为en
Environment.EnvProp('languageCode', 'en');

使用@StorageProp

Environment.EnvProp('languageCode', 'en');
let enable = AppStorage.Get('languageCode');

@Entry
@Component
struct Index {
  @StorageProp('languageCode') languageCode: string = 'en';

  build() {
    Row() {
      Column() {
        // 输出当前设备的languageCode
        Text(this.languageCode)
      }
    }
  }
}

@Watch

监听状态变化,不要在async await异步函数中使用

@Component
struct TotalView {
  @Prop @Watch('onCountUpdated') count: number;
  @State total: number = 0;
  // @Watch cb
  onCountUpdated(propName: string): void {
    this.total += this.count;
  }

  build() {
    Text(`Total: ${this.total}`)
  }
}

@Entry
@Component
struct CountModifier {
  @State count: number = 0;

  build() {
    Column() {
      Button('add to basket')
        .onClick(() => {
          this.count++
        })
      TotalView({ count: this.count })
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容