使用 Navigation 进行页面跳转,当已经在某个name为“Page01”的页面时,再在同一时刻先pop再push一个name相同的页面,会发现页面没有发生跳转,示例如下:

Button(`pop, push Page01 (normal)`).width('80%').margin({ top: 10, bottom: 10 })
  .onClick(() => {
    this.pathStack?.pop();
    this.pathStack?.pushPath({ name: 'Page01' });
  })

效果如下:

这是因为连续调用多个页面栈操作方法时,中间过程会被忽略,显示最终的栈操作结果。

而上述操作栈顶页面已经为“Page01”,pop后再push“Page01”,栈中页面无变化,所以页面不会发生跳转。

要想在这个场景pop已经存在的“Page01”,并且push一个新的“Page01”,需要设置 launchMode 为 NEW_INSTANCE,示例如下:

Button(`pop, push Page01 (new)`).width('80%').margin({ top: 10, bottom: 10 })
  .onClick(() => {
    this.pathStack?.pop();
    this.pathStack?.pushPath({ name: 'Page01' }, { launchMode: LaunchMode.NEW_INSTANCE });
  })

这样就能正常 push 一个新的“Page01”,效果如下:

完整示例如下:

@Component
struct Page01 {
  pathStack: NavPathStack | undefined = undefined;

  build() {
    NavDestination() {
      Button(`pop, push Page01 (normal)`).width('80%').margin({ top: 10, bottom: 10 })
        .onClick(() => {
          this.pathStack?.pop();
          this.pathStack?.pushPath({ name: 'Page01' });
        })
      Button(`pop, push Page01 (new)`).width('80%').margin({ top: 10, bottom: 10 })
        .onClick(() => {
          this.pathStack?.pop();
          this.pathStack?.pushPath({ name: 'Page01' }, { launchMode: LaunchMode.NEW_INSTANCE });
        })
    }.title('页面1')
    .onReady((context: NavDestinationContext) => {
      this.pathStack = context.pathStack;
    })
  }
}

@Entry
@Component
struct Index {
  pagesStack: NavPathStack = new NavPathStack();

  @Builder
  pagesMap(name: string) {
    if (name == 'Page01') {
      Page01()
    }
  }

  build() {
    Navigation(this.pagesStack) {
      Button('push 页面1').width('80%').margin({ top: 10, bottom: 10 })
        .onClick(() => {
          this.pagesStack.pushPathByName('Page01', '');
        })
    }.title('主页面')
    .titleMode(NavigationTitleMode.Mini)
    .navDestination(this.pagesMap)
  }
}
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐