HarmonyOS使用@ObjectLink 数据不刷新

一个接口返回的Json转换后的集合,在@Component export struct UserDeviceItem { @ObjectLink item: DeviceModel } item的数据变化,页面没有刷新,是必须要new的才行?如何解决json转换使用的问题?

HarmonyOS
2024-08-09 11:20:50
浏览
收藏 0
回答 2
待解决
回答 2
按赞同
/
按时间
一路向北545
分享
微博
QQ
微信
回复
2024-08-09 11:23:42
put_get

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

// 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-08-09 18:19:05
相关问题
修改ForEach使用数据对象,UI刷新
767浏览 • 1回复 待解决
IF条件变化后UI刷新
361浏览 • 1回复 待解决
HarmonyOS List组件动态刷新数据问题
81浏览 • 1回复 待解决
状态装饰器 ui刷新的问题
2110浏览 • 1回复 待解决
HarmonyOS 数据改变未刷新页面
183浏览 • 0回复 待解决
在自定义组件中使用@ObjectLink报错
367浏览 • 1回复 待解决
HarmonyOS使用Refresh下拉刷新问题
233浏览 • 1回复 待解决
前端手动刷新显示Rdb数据
565浏览 • 1回复 待解决