HarmonyOS鸿蒙Next中如何解决JSON强转为对象后,页面刷新失败

HarmonyOS鸿蒙Next中如何解决JSON强转为对象后,页面刷新失败

【问题现象】

JSON串使用as直接转换为对象,该对象用[@ObjectLink](/user/ObjectLink)修饰,直接修改该对象的属性时,系统无法感知到属性变化,导致列表页面无法渲染刷新。

【背景知识】

【解决方案】

通过JSON.parse得到的对象并不是类构造出的实例,其数据变化无法被观测到,所以不能实现UI刷新。如果想实现UI刷新,有以下两种实现方式:

  • 可以通过将所有JSON对象按照new的方式转换为具体的对象,转换后对象的数据变化就可以被观测到了,代码如下:

    let newUsers: User[] = []
    data.users?.forEach((item: User) => {
      let newUser = new User(item) // 重新赋值
      newUsers.push(newUser)
    })
    
  • 可以通过使用三方库的方式,把JSON转换成具体的对象,转换后对象的数据变化就可以被观测到了。使用三方库前,需要先执行如下命令安装依赖三方库:

    ohpm install reflect-metadata
    ohpm i class-transformer
    

    三方库安装完成后,具体转换对象的代码如下:

    [@Entry](/user/Entry)
    [@Component](/user/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%')
      }
    }
    
    [@Component](/user/Component)
    export struct ViewA {
      [@ObjectLink](/user/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})
      }
    }
    
    [@Observed](/user/Observed)
    export class TestA {
      public str: string
    
      constructor(str: string) {
        this.str = str;
      }
    }
    
    class ResponseObj {
      @Type(() => Person)
      data: Person[] = [];
    }
    

最终效果如下:

点击放大


更多关于HarmonyOS鸿蒙Next中如何解决JSON强转为对象后,页面刷新失败的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中如何解决JSON强转为对象后,页面刷新失败的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


通过JSON.parse得到的对象无法被观测到,导致UI无法刷新。解决方案有两种:

  1. 使用new将JSON对象转换为具体对象:

    let newUsers: User[] = []
    data.users?.forEach((item: User) => {
      let newUser = new User(item) // 重新赋值
      newUsers.push(newUser)
    })
    
  2. 使用三方库class-transformer将JSON转换为具体对象:

    ohpm install reflect-metadata
    ohpm i class-transformer
    

    转换代码:

    let responseObj: ResponseObj = plainToClass(ResponseObj, jsonString)
    this.list = this.list.concat(responseObj.data)
    
回到顶部