目录

图片展示页面,图片序号显示有误

问题现象

在Web页面点击图片进入图片展示页面,图片序号显示有误,比如应该显示为“1/3”,实际显示为“01/3”。且只有在刚进入页面时出现,图片滑动后就恢复正常。

问题效果预览:

背景知识

问题定位

  1. 通过问题复现,原有逻辑是图片展示页面的标题显示为“当前第几张图片/图片总数”,其中“当前第几张图片”是在Web网页中点击当前图片的索引加1得到。所以标题字符串生成:
    let currentIndex:number = 0
    let imageArr:string[] = []
    let titleStr = (currentIndex + 1) + '/' + imageArr.length
  2. 初次显示成“01/3”,主要的原因是currentIndex虽然定义为number类型,但是赋值给它的数据实际可能是string类型。在JSON解析中会出现这样的问题。例如,将jsonStr中string类型的"currentIndex"通过JSON.parse解析后赋值给number类型的currentIndex,使用===判断发现数据类型并不相同,返回false,currentIndex还是原来的类型。
    let jsonStr = '{"currentIndex" : "2", "totalCount" : 4}';
    // json字符串转Record对象
    let data0: Record<number, string> = JSON.parse(jsonStr) as Record<number, string>;
    let currentIndex: number = data0['currentIndex'];
    if (currentIndex === 2) {
      console.info('The type of currentIndex is number');
    } else {
      console.info('The type of currentIndex is not number');
    }
  3. 滑动后显示恢复,通过日志分析,因为UI布局使用的Swiper组件。给currentIndex赋值的是Swiper的index,index是number类型。
    [(100000:100000:scope)] Swiper FireUnselectedEvent id:915, index:1
    [(100000:100000:scope)] Swiper FireUnselectedEvent id:915, index:2
    [(100000:100000:scope)] Swiper FireUnselectedEvent id:915, index:3

分析结论

修改建议

JSON.parse解析并不会修改目标字符串的数据类型为解析指定的数据类型,"currentIndex"解析前是string类型,使用JSON.parse解析后仍然是string类型。需要使用强制类型转换Number()后再赋值。

@Entry
@Component
struct StringChange {
  @State message: string = 'Hello World';

  aboutToAppear(): void {
    let jsonStr = '{"currentIndex" : "2", "totalCount" : 4}';
    // json字符串转Record对象
    let data0: Record<number, string> = JSON.parse(jsonStr) as Record<number, string>;
    let currentIndex: number = Number(data0['currentIndex']);
    if (currentIndex === 2) {
      console.info('The type of currentIndex is number');
    } else {
      console.info('The type of currentIndex is not number');
    }
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('Index1HelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.message = 'Welcome';
        })
    }
    .height('100%')
    .width('100%')
  }
}