目录

NavPathStack跳转不存在页面时重定向

问题现象

NavPathStack跳转不存在的页面如何能拦截,然后重定向到一个“敬请期待”自定义页面?

效果预览

背景知识

Navigation组件是路由导航的根视图容器,一般作为Page页面的根容器使用。NavPathStack是Navigation路由栈,可以通过多种方法跳转至指定的NavDestination页面。

解决方案

使用pushDestination、pushDestinationByName方法进行页面跳转,捕捉跳转的回调结果,若跳转错误则重定向至指定页面。

import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct NavPathStackDemo {
  navPathStack: NavPathStack = new NavPathStack();

  @Builder
  pageMap(name: string) {
    if (name === 'ErrorPage') {
      ErrorPage();
    }
  }

  build() {
    Navigation(this.navPathStack) {
      Button('跳转不存在页面')
        .fontSize('20fp')
        .margin({ top: '50vp' })
        .onClick(() => {
          // 跳转xxx页面,此页面不存在
          this.navPathStack.pushDestination({ name: 'xxx' }).catch((result: BusinessError) => {
            console.info(`${result.code} ${result.name} ${result.message}`);
            this.navPathStack.pushPathByName('ErrorPage', null, false); // 跳转失败重定向
          });
        });
    }
    .navDestination(this.pageMap)
    .height('100%')
    .width('100%');
  }
}

@Component
struct ErrorPage {
  build() {
    NavDestination() {
      Text('敬请期待')
        .fontSize('50fp')
        .margin({ top: '50vp' });
    }.height('100%').width('100%');
  }
}