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