HarmonyOS ObjectLink问题

父组件:A变量

@State wordList:WordList[] =[]

for循环产生创建子组件

ForEach(this.wordList,(itemBeanStr:WordList,index:number)=> {
  WordCardItem(itemBean:itemBeanStr)
})

子组件:B

@ObjectLink  itemBean:WordList   //变量

WordList 在WordCardBean.ets文件中

export class WordCardBean {
  currentCnWordReadPosition: number =0
  currentWordReadPosition: number =0
  wordList: WordList[] =[]
  cnWordList: WordList[] =[]
}

@Observed
export class WordList {
  audio: string =''
  audioAddress: string =''
  cnExplanation: string=''
  enExplanation: string=''
  exampleSentence: string=''
  id: number=0
  partOfSpeech: string=''
  phoneticSymbolEn: string=''
  phoneticSymbolUs: string=''
  score: number =0
  word: string=''
  wordPic: string=''
}

当改变wordList某个下标中的属性时候,发现子组件布局没有刷新

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

场景是使用数组对象,数组里的对象的属性变化了ui没有更新是吗,这种的话可以通过引入三方库 reflect-metadata 和 class-transformer实现,参考如下demo:

//TestJson.ets
import { plainToClass, Type } from 'class-transformer';
import 'reflect-metadata';
import { Person, ViewA } from './ViewA';

class ResponseObj {
  @Type(() => Person)
  data: Person[] = [];
}

@Entry
@Component
struct TestJson {
  @State list: Person[] = [];
  @State message: string = 'Click me';

  aboutToAppear(): void {
    let str = '{"data" : [{"number" :1,"age": 20, "testA": { "str" : "123"}},{"number" :2,"age": 21,"testA": {"str" : "456"}}]}'
    let jsonData: ESObject = JSON.parse(str)
    let responseObj: ResponseObj = plainToClass(ResponseObj, jsonData);
    console.log(` ${responseObj.data[0] instanceof Person}`)
    this.list = this.list.concat(responseObj.data);
  }

  build() {
    Row() {
      Column() {
        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 })
  }
}

可以使用ohpm 引入三方库

ohpm install class-transformer
ohpm install reflect-metadata
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS ObjectLink使用
20浏览 • 1回复 待解决
HarmonyOS V2 @ObjectLink?
229浏览 • 0回复 待解决
HarmonyOS @ObjectLink到底怎么用
58浏览 • 1回复 待解决
Observe和ObjectLink 使用
292浏览 • 1回复 待解决
HarmonyOS使用@ObjectLink 数据不刷新
801浏览 • 2回复 待解决
HarmonyOS @ObjectLink和@State的相关疑问
294浏览 • 1回复 待解决
HarmonyOS 状态管理之ObjectLink的疑问
81浏览 • 1回复 待解决
在自定义组件中使用@ObjectLink报错
1351浏览 • 1回复 待解决