HarmonyOS 嵌套自定义类型引用的undefined判断

export class TestA {
  one: string = "";
  two: string = "";
  three: TestB = new TestB()
}

export class TestB {
  aaa: string = "";
  bbb: TextC = new TextC();
  ccc: string = "";
}

export class TextC {
  ddd: string = "";
  fff: string = "";
  eee: string = "";
}

有如上三个自定义类型,在page中做这样的引用时 this.info.three.ccc 总是报undefined的错误:

Error message:Cannot read property ccc of undefined
struct Index {
  @State message: string = 'Hello World';
  @State info: TestA = {} as TestA

  build() {
    RelativeContainer() {
      Text(this.info.three.ccc)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

@State info初始化不对相当于一个空对象,改为@State info: TestA = new TestA()即可,示例参考:

export interface ProDetailBaseInfo {
  customer_company_address: ProCustomerCompanyAddres;
}

export interface ProCustomerCompanyAddres {
  company_address: string;
  calculate_commute_time: number;
  transport_type_name: string
}

export class TestA {
  one: string = "";
  two: string = "";
  three: TestB = new TestB()
}

export class TestB {
  aaa: string = "";
  bbb: TextC = new TextC();
  ccc: string = "1111";
}

export class TextC {
  ddd: string = "";
  fff: string = "";
  eee: string = "";
}

@Entry
@Component
struct Index8 {
  @State message: string = 'Hello World';
  @State detail: ProDetailBaseInfo =
    { customer_company_address: { company_address: '', calculate_commute_time: 0, transport_type_name: '' } }
  @State transportString: string = ''
  @State info: TestA = new TestA()

  aboutToAppear(): void {
    let seconds: number = 0
    if (this.detail) {
      let ccaddress: ProCustomerCompanyAddres = this.detail.customer_company_address
      if (ccaddress) {
        seconds = ccaddress.calculate_commute_time
        this.transportString = ccaddress.transport_type_name + '约' + seconds.toString()
      }
    }
  }

  build() {
    RelativeContainer() {
      Text(this.info.three.ccc)
        .id('Index8HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 如何判断自定义类型
41浏览 • 1回复 待解决
HarmonyOS 引用自定义web模块问题
851浏览 • 1回复 待解决
HarmonyOS 跨模块引用自定义组件
36浏览 • 1回复 待解决
自定义弹窗如何嵌套使用
1724浏览 • 1回复 待解决
自定义组件嵌套子组件
9555浏览 • 3回复 待解决
HarmonyOS 播放条支持自定义多种类型
342浏览 • 1回复 待解决
HarmonyOS引用不支持自定义对象吗
66浏览 • 1回复 待解决
Hvigor自定义编译任务如何引用三方库
1255浏览 • 1回复 待解决
自定义弹窗自定义转场动画
1170浏览 • 1回复 待解决