HarmonyOS @ObservedV2和@Trace是不是不能用在json序列化出来的对象上?

服务端接口返回的数据是经过json生成的对象,在这个对象上面使用@ObservedV2和@Trace会刷新UI失败,但是如果深拷贝一个对象后再使用@ObservedV2和@Trace就会刷新UI成功,所以@ObservedV2和@Trace是不是不能用在json序列化出来的对象上?

HarmonyOS
2024-12-25 08:43:04
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

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

// test.ts 
export let jsonString:Record<string, ESObject> = {
  "data" : [
    {
      "number" :1,
      "age": 20,
      "testA": {
        "str" : "123"
      }
    },
    {
      "number" :2,
      "age": 21,
      "testA": {
        "str" : "456"
      }
    }
  ]
}
// Index.ets
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
微信
回复
2024-12-25 10:16:52
相关问题
HarmonyOS @ObservedV2不支持{} as Father对象
233浏览 • 1回复 待解决
HarmonyOS http请求,json序列化
303浏览 • 1回复 待解决
HarmonyOS JSONmap结构如何序列化
809浏览 • 1回复 待解决
求大佬告知如何序列化对象
1067浏览 • 1回复 待解决