鸿蒙开发——响应式数据持久化

 数据增加之后 渲染的数据也增加

import { BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';
import { App } from '@kit.ArkUI';

class  punchRecord{
  time: string=''
  local: string=''

  constructor(time: string='',local: string='') {
    this.time=time
    this.local=local
  }
}

//持久化存储
PersistentStorage.persistProp('aa',new punchRecord())


@Entry
@Component
struct DakaPage {

  // 打卡按钮点击处理函数
  onPunchCard(): void {

    this.getCurrentLocation().then((location) => {
      this.time = new Date().toLocaleString();
      // console.info('aabb',this.time)
      this.local = `Lat: ${location.latitude}, Lng: ${location.longitude}`;
      // console.info('aabb',this.local)
      // 将新记录添加到打卡记录数组
      let pun:punchRecord=new punchRecord(this.time,this.local)
      this.punchRecords.push(pun);
      console.info('aacc',JSON.stringify(this.punchRecords))

      // 保存打卡记录到本地存储
      AppStorage.setOrCreate('aa',this.punchRecords)
      console.log('aab',JSON.stringify(this.punchRecords))

      // 更新界面
      // this.update();
    }).catch((error:BusinessError) => {
      console.error('Failed to get location: ' + JSON.stringify(error));
    });
  }
  //更新界面
  update(){}
  // 获取当前地理位置
  async getCurrentLocation(): Promise<geoLocationManager.Location> {
    const request: geoLocationManager.SingleLocationRequest = {
      locatingPriority: geoLocationManager.LocatingPriority.PRIORITY_LOCATING_SPEED,
      locatingTimeoutMs: 10000
    };
    this.local= JSON.stringify(await geoLocationManager.getCurrentLocation(request))
    return await geoLocationManager.getCurrentLocation(request);
  }

  // 定义一个打卡记录数组,数组中的每个元素都是包含 time 和 location 的对象
  @State punchRecords: punchRecord[]= []
  // @State arr: punchRecord= new punchRecord()
  @State local:string=''
  @State time:string=''
  //取出数据
  @StorageProp('aa') aa:punchRecord[]=[]



  // 界面构建
  build() {
    Column() {
      Button('打卡')
        .onClick(() => this.onPunchCard())
        .width('100%')
        .height(50)
        .backgroundColor('#00AAFF')
        .fontColor('#FFFFFF')
        .margin({ top: 20 })
//如果数组存在就显示
        if (this.aa[0]){
          ForEach(this.aa, (item: punchRecord) => {
            Column(){
              Text(`打卡时间: ${item.time}`)
              Text(`地理位置: ${item.local}`)
                .fontSize(14)
                .fontColor('#666666')
                .margin({ bottom: 10 })
            } .backgroundColor(Color.Pink).height(40)
            .width('90%')
          })
        }


    }.height('100%')
    .width('100%')
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值