HarmonyOS Foreach循环渲染默认的key有问题

Foreach循环渲染默认的key有问题,如果函数缺省,框架默认的键值生成函数为:

(item: T, index: number) => { return index + '__' + JSON.stringify(item);  
  • 1.

日志输出为: index_[] 这个JSON.stringify(item)没有转化成item的JSON字符串,导致item的数据更新了,但是item视图没有重新渲染。

HarmonyOS
2024-12-25 12:58:35
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zbw_apple

对于ObserverV2和Trace装饰的对象如何转成json字符串,参考以下示例:

import { plainToClass } from "class-transformer";

@ObservedV2
class Son {
  @Trace age: number = 100;
}

class Father {
  son: Son = new Son();
}

@Entry
@Component
struct Index {
  father: Father = new Father();

  aboutToAppear(): void {
    let a = JSON.stringify(this.father);
    let b: Father = plainToClass(Father, this.father);
    //{"son":{"__ob_age":100}}替换成{"son":{"age":100}}
    console.log(JSON.stringify(convertKeysToCamelCase(this.father)))
  }

  build() {
    Column() {
      // 当点击改变age时,Text组件会刷新
      Text(`${this.father.son.age}`)
        .fontSize(40)
        .onClick(() => {
          this.father.son.age++;
        })
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
// utils.ets
export function underscoreToCamelCase(underscoreString: string): string {
  // 捕获_ob替换成''
  return underscoreString.replace(/(_ob)/g, (match: string, letter: string): string => {
    console.log(letter)
    return '';
  });
}

export function convertKeysToCamelCase(obj: ESObject): ESObject {
  if (obj && typeof obj === 'object') {
    const newObj: ESObject = {};
    Object.keys(obj).forEach((key) => {
      if (obj.hasOwnProperty(key)) {
        const newKey = underscoreToCamelCase(key);
        newObj[newKey] = convertKeysToCamelCase(obj[key]);
      }
    })
    return newObj;
  } else {
    return obj;
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
分享
微博
QQ
微信
回复
2024-12-25 15:29:13


相关问题
ForEach循环渲染过程是什么样
1716浏览 • 1回复 待解决
HarmonyOS forEach return退出循环
902浏览 • 1回复 待解决
HarmonyOS forEach如何提前终止循环
753浏览 • 1回复 待解决
HarmonyOS lazyForEachkey问题
471浏览 • 1回复 待解决
HarmonyOS ForEach创建视图刷新问题
622浏览 • 1回复 待解决
HarmonyOS ForEach列表刷新问题
936浏览 • 1回复 待解决
HarmonyOS Swiper+ForEach使用问题
1220浏览 • 1回复 待解决
如何排查循环引用问题
1651浏览 • 1回复 待解决