HarmonyOS鸿蒙Next中Navigation跳转中pushPathByName传的参数目标页面怎么获取
HarmonyOS鸿蒙Next中Navigation跳转中pushPathByName传的参数目标页面怎么获取 这是从引导页跳转到登录的一个小测试,我想通过 pushPathByName 的第二参数实现数据传参到登录页面,登录页面接收应该怎么写
Lead页面

Login页面,写了getParamByName无法获取传参

更多关于HarmonyOS鸿蒙Next中Navigation跳转中pushPathByName传的参数目标页面怎么获取的实战教程也可以访问 https://www.itying.com/category-93-b0.html
【背景知识】
- 组件导航(Navigation):主要用于实现Navigation页面(NavDestination)间的跳转,支持在不同Navigation页面间传递参数,提供灵活的跳转栈操作,从而更便捷地实现对不同页面的访问和复用。
- pushPathByName:将name指定的NavDestination页面信息入栈,传递的数据为param。
- onReady:当NavDestination即将构建子组件之前会触发此回调。
【解决方案】
- 传递参数:源页面可通过pushPath、pushPathByName、pushDestination等接口指定页面跳转,本例以pushPathByName接口举例说明,pushPathByName可通过入参指定目标页面(name)、**传递参数(param)**等。
- 接收参数:目标页面可通过NavDestination的onReady回调函数接收源页面传递的参数,也可在组件的生命周期函数aboutToAppear中通过NavPathStack的getParamByIndex、getParamByName等接口获取源页面传递的参数。
以onReady回调函数为例:
@Entry
@Component
struct Index {
  pathStack: NavPathStack = new NavPathStack();
  build() {
    Navigation(this.pathStack) {
      Column() {
        Button('Push PageOne', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            let item:string='hello world'
            this.pathStack.pushPathByName('pageOne', item);
          })
      }.width('100%').height('100%')
    }
    .title("Navigation")
    .mode(NavigationMode.Stack)
  }
}
@Builder
export function PageOneBuilder() {
  PageOne();
}
@Component
export struct PageOne {
  pathStack: NavPathStack = new NavPathStack();
  @State textShow: string = ''
  build() {
    NavDestination() {
      Column() {
        Text(this.textShow)
          .fontSize(30)
        Button('回到首页', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pathStack.clear();
          })
      }.width('100%').height('100%')
    }.title('PageOne')
    .onReady((context: NavDestinationContext) => {
      this.pathStack = context.pathStack;
      this.textShow=context.pathInfo.param as string
    })
  }
}
以getParamByName为例, 其中的name参数需要是目标页面名,以下是具体代码:
@Entry
@Component
struct Index {
  pathStack: NavPathStack = new NavPathStack();
  build() {
    Navigation(this.pathStack) {
      Column() {
        Button('Push PageOne', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            let item: string = 'hello world';
            this.pathStack.pushPathByName('pageOne', item);
          });
      }.width('100%').height('100%');
    }
    .title("Navigation")
    .mode(NavigationMode.Stack);
  }
}
@Builder
export function PageOneBuilder() {
  PageOne();
}
@Component
export struct PageOne {
  pathStack: NavPathStack = new NavPathStack();
  @State textShow: string = '';
  build() {
    NavDestination() {
      Column() {
        Text(this.textShow)
          .fontSize(30);
        Button('回到首页', { stateEffect: true, type: ButtonType.Capsule })
          .width('80%')
          .height(40)
          .margin(20)
          .onClick(() => {
            this.pathStack.clear();
          });
      }.width('100%').height('100%');
    }.title('PageOne')
    .onReady((context: NavDestinationContext) => {
      this.pathStack = context.pathStack;
      this.textShow = this.pathStack.getParamByName('pageOne')[0] as string;
    });
  }
}
更多关于HarmonyOS鸿蒙Next中Navigation跳转中pushPathByName传的参数目标页面怎么获取的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
可以通过下面这个方法获取
const pageStack = new NavPathStack() 
const params = await pageStack.getParamByName('PersonalDataView')[0] as PlayerProfileType
把目标页面和类型替换一下即可
具体参考官方文档:Navigation
背景知识:
楼主首先你需要了解到 NavPathStack、Navigation(首页) 和 NavDestination(二级页面) 之前的关系,其中NavPathStack是将页面Navigation和NavDestination进行串在一起的。在 NavPathStack 下面有跳转方法:如navPathStack.pushPathByName()等用于跳转页面使用。
详情可查询:Navigation指南
问题解决:
处理上述问题只需要在方法:navPathStack.pushPathByName(“NAME”,参数) 。如下代码:
//首页:
@Entry
@ComponentV2
struct AppStorageV2Page {
    @Local prop: Sample | undefined = AppStorageV2.connect(Sample, () => new Sample())
    pageStack: NavPathStack = new NavPathStack()
    aboutToAppear(): void {
    }
    build() {
        Navigation(this.pageStack) {
            Column() {
                Button('跳转到page2')
                    .onClick(() => {
                        let user:UserProfileItem = {
                            title: "名称",
                            icon: $r("app.media.app_icon"),
                            userId:"123456"
                        }
                        //1、跳转加传参数,这里以对象为例,还可以字符串等
                        this.pageStack.pushPathByName('Page2Page',user );
                    })
            }
        }
    }
}
//二级页面
@Entry
@ComponentV2
struct Page2Page {
    pageStack: NavPathStack = new NavPathStack()
    @Local data:UserProfileItem = {
        title: "",
        icon: $r("app.media.app_icon"),
        userId: ""
    }
    aboutToAppear(): void {
    }
    @Builder
    build() {
        NavDestination() {
            //2、展示页面数据
            Button('Page2页面:'+JSON.stringify(this.data))
                .onClick(() => {
                })
        }.onReady((context: NavDestinationContext) => {
            this.pageStack = context.pathStack
            //1、获取首页中的参数 pushPathByName('Page2Page',user ); user,切记需要进行对应类型强转
            this.data = context.pathInfo.param as UserProfileItem
        })
    }
}
真机演示:

页面路由是App研发过程常用的能力,是App运行的基础能力,支持页面之间的切换。
在鸿蒙系统中提供NavPathStack组件,支持页面路由导航。
下面的代码中实现打开子页面时父页面向子页面传参数,仅是关键部分代码。
父页面(Index.ets)文件中的实现
struct Index {
  pageStack: NavPathStack = new NavPathStack();
  build() {
    Navigation(this.pageStack) {
      Column() {
        // 父视图实现,打开子视图,并传参数
        Button('nav pushPath SecondPage_Nav have param')
          .onClick(() => {
            // this.pageStack是NavPathStack对象
            this.pageStack.pushPathByName('secondPageNav', "Index");
          })
      }
    }
    .hideTitleBar(true)
  }
}
子页面(SecondPage_Nav.ets)文件中的实现
struct SecondPage_Nav {
  pageStack: NavPathStack = new NavPathStack();
  build() {
    NavDestination() {
    }
    .title('SecondPage_Nav')
    .onReady((context: NavDestinationContext) => {
      this.pageStack = context.pathStack;
      // 方案1:context.pathInfo.param = “Index”
      if (context.pathInfo.param) {
        console.log(context.pathInfo.param as string)
      }
      // 方案2:this.pageStack.getParamByName("secondPageNav")[0] = “Index”
      // 但要注意,如有多个secondPageNav页面实例时[0]中的0需要调整。
      if (this.pageStack.getParamByName("secondPageNav")[0]) {
        console.log(this.pageStack.getParamByName("secondPageNav")[0] as string)
      }
    })
  }
}
也可以在@Builder函数中设置两个参数(name,param)
例如:
[@Builder](/user/Builder)
export function PublicUserPageBuilder(_name: string, param: Object | undefined){
  PublicUserPage({Param: param})
}
@Component
export struct PublicUserPage{
  @State Param: Object | undefined = 0
  build(){
    ......
  }
}
这样也可以解决你的问题

可以通过Navdestination的onReady事件中拿到
楼主可以参考这个写法:getParamByName后面携带的参数名应该是Login页面的页面名称才对
Button('get', { stateEffect: true, type: ButtonType.Capsule })
  .width('80%')
  .height(40)
  .margin(20)
  .onClick(() => {
    console.info('-------------------');
    console.info(`获取栈中所有NavDestination页面的名称 ${JSON.stringify(this.pageInfos.getAllPathName())}`);
    console.info(`获取index指定的NavDestination页面的参数信息 ${JSON.stringify(this.pageInfos.getParamByIndex(1))}`);
    console.info(`获取全部名为name的NavDestination页面的参数信息 ${JSON.stringify(this.pageInfos.getParamByName('pageTwo'))}`);
    console.info(`获取全部名为name的NavDestination页面的位置索引 ${JSON.stringify(this.pageInfos.getIndexByName('pageOne'))}`);
    console.info(`获取栈大小 ${JSON.stringify(this.pageInfos.size())}`);
  })
参考文档:Navigation-导航与切换-ArkTS组件-ArkUI(方舟UI框架)-应用框架 - 华为HarmonyOS开发者
一楼说的对,具体一些就是你的Login页面,getParamByName传参应该传的是’Login’,你获取的是目标页的参数,不是前一个页面的。
name字段应该写成一样的吧!
在HarmonyOS Next中,使用pushPathByName跳转时传递的参数可通过目标页面的aboutToAppear或onPageShow生命周期函数获取。参数存储在页面路由参数对象中,使用router.getParams()方法读取。例如,在目标页面中通过router.getParams().paramName访问具体参数值。确保参数名与传递时一致,即可直接获取数据。
在HarmonyOS Next中,通过pushPathByName传递参数后,目标页面需要使用路由参数解析API获取参数。具体步骤如下:
- 
传递参数(Lead页面): import { router } from '[@kit](/user/kit).RouterKit'; // 通过params传递参数对象 router.pushPathByName({ name: 'LoginPage', params: { key1: 'value1', key2: 'value2' } });
- 
接收参数(Login页面): import { router } from '[@kit](/user/kit).RouterKit'; // 在页面onPageShow或aboutToAppear生命周期中获取 onPageShow() { const params = router.getParams() as Record<string, Object>; if (params) { const value1 = params['key1']; // 获取具体参数值 const value2 = params['key2']; } }
注意:
- 使用router.getParams()获取完整参数对象
- 参数类型需通过as进行类型断言
- 建议在页面显示生命周期钩子中处理参数
- 确保目标页面已在main_pages.json中注册路由名称
你代码中使用getParamByName方法不正确,应改用router.getParams()获取参数对象后通过键名访问具体值。
 
        
       
                   
                   
                  

