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 })
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
分享
微博
QQ
微信
回复
2024-12-25 10:16:52
相关问题
HarmonyOS @ObservedV2不支持{} as Father对象
825浏览 • 1回复 待解决
HarmonyOS http请求,json序列化
1128浏览 • 1回复 待解决
HarmonyOS JSONmap结构如何序列化
1646浏览 • 1回复 待解决
求大佬告知如何序列化对象
1966浏览 • 1回复 待解决