HarmonyOS ObservedV2装饰器对接口返回的model进行状态监听无效

ObservedV2装饰器对接口返回的model进行状态监听无效

HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

通过JSON.parse得到的对象并不是通过User构造出的实例,其数据变化无法被观测到,所以不能实现ui刷新 可以通过引入三方库 reflect-metadata 和 class-transformer,参考如下demo实现,observedv2同理

//test.ets
export let jsonString:Record<string, ESObject> = {
  "data" : [
    { "number" :1,
      "age": 20,
      "testA": {
        "str": "123"
      }
    },
    {
      "number" :2,
      "age": 21,
      "testA": {
        "str": "456"
      }
    }
  ]
}
import { Type, plainToClass } from 'class-transformer'
import 'reflect-metadata'
import { jsonString } from './test'
import { TestA, Person, ViewA} from './ViewA';
class ResponseObj {
  @Type (() => Person) data: Person[] = [];
}
@Entry @Component struct Index {
  @State list: Person[] = [];
  @State message: string = 'Click me';
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(40)
          .onClick(() => {
            let responseObj : ResponseObj = plainToClass(ResponseObj, jsonString);
            console.log(` ${responseObj.data[0] instanceof Person}`)
            this.list = this.list.concat(responseObj.data); })
        ForEach(this.list, (item : Person, index: number) => {
          ViewA({index:index, testA: item.testA})
        })
      }
      .width('100%')
    } .height('100%')
  } }
ViewA.ets
import { Type } from 'class-transformer'
@Observed export class TestA {
  public str : string
  constructor(str: string) { this.str = str; }
}
export class Person {
  name: string = ''
  age: number = 1
  @Type(()=>TestA) testA: TestA = new TestA('')
}
@Component export struct ViewA {
  @ObjectLink testA: TestA
  index: number = -1;
  build() {
    Row(){
      Button(`View A ${this.testA.str}`)
        .onClick(() =>{
          this.index += 1;
          this.testA.str = `${this.index} : Test A String` })
    }
    .margin({top : 10 })
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
父组件如何与孙子组件进行状态同步
2702浏览 • 1回复 待解决
HarmonyOS 钱包NFC接口对接
360浏览 • 1回复 待解决
状态装饰 ui不刷新问题
2465浏览 • 1回复 待解决