HarmonyOS 鸿蒙Next中HMRouter如何传参?

HarmonyOS 鸿蒙Next中HMRouter如何传参?

代码如下,为啥B页面获取不到参数呢?

是按照文档示例写的!

cke_137.png

cke_414.png


更多关于HarmonyOS 鸿蒙Next中HMRouter如何传参?的实战教程也可以访问 https://www.itying.com/category-93-b0.html

9 回复

你好,可以取到参数,传参你写的也没问题,只是取的时候少了参数,正确如下:

cke_782.png

cke_1072.png

更多关于HarmonyOS 鸿蒙Next中HMRouter如何传参?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


标题

这是段落文本。

这是另一段落文本。

  1. 一般使用的参数传递方法:
//传参
HMRouterMgr.push({
  pageUrl: PageConstant.WebNewWindow,
  param: param,
})
  1. 接受参数:
let res = HMRouterMgr.getCurrentParam() as NewWindowPageParam
if (res) {
  this.param = res
  LogUtil.i('WebNewWindow:aboutToAppear', this.param)
}

我们常用的方法是上面这种

  1. 进阶用法:获取pop页面携带的参数信息
HMRouterMgr.push({
  pageUrl: PageConstant.SelectArea,
}, {
  onResult: (popInfo: HMPopInfo) => {
    let popResult: AreaParam = popInfo.result as AreaParam
    if (popResult) {
      // this.currentArea = popResult.currentArea
    }
  }
})

好的好的,受教了~~,

跳转时传递参数:

HMRouterMgr.push({

  pageUrl: 'BPage', // 这里与目标页面的@HMRouter配置一致

  navigationId: "mainNavigationId",

  param: { id: 123, data: 'test' } // 参数要是可序列化对象

})

目标页面接收参数:

@Component
@HMRouter({ pageUrl: 'BPage' }) // 这里要与push的pageUrl匹配
struct BPage {

  @State param: object | null = null;

  aboutToAppear() {

    this.param = HMRouterMgr.getCurrentParam(); // 这里要在此生命周期获取

  }
}

HMRouterMgr.push({ navigationId: “mainNavigation”, pageUrl: “TwoPage”, param: new PageModel(“张三”, “12”) })

这样传参就可以,那官方的文档有问题吗?还是我的用法不对!

cke_829.png

在HarmonyOS鸿蒙Next中,HMRouter传参使用withParams()方法添加键值对参数。示例:

router.pushUrl({
  url: 'pages/TargetPage',
  params: { key1: 'value1', key2: 123 }
})

目标页面通过router.getParams()获取参数:

let params = router.getParams() as { key1: string; key2: number }

参数支持字符串、数字等基本类型,对象需序列化。页面跳转时参数会保留在路由栈中。

从代码截图来看,问题可能出在参数传递方式上。在HMRouter中,参数传递有两种常见方式:

  1. 通过URL参数传递:
HMRouter.pushUrl({
  url: 'pages/B',
  params: {id: 123}  // 这里参数应该放在params对象中
});
  1. 在B页面获取参数时,应该使用:
const params = HMRouter.getParams();
const id = params?.id;  // 使用可选链操作符避免空值

从截图看,您可能直接在URL中拼接了参数(如pages/B?id=123),但同时又使用了params对象传递。建议统一使用其中一种方式,推荐使用params对象传递更规范。

另外请检查:

  1. 页面路由是否正确定义了参数接收
  2. 确保HMRouter版本是最新的
  3. 参数类型是否匹配(如传递数字但接收字符串)
回到顶部