鸿蒙NEXT-HMRouter,在使用router后无法跳转问题解决

发布于:2025-06-15 ⋅ 阅读:(20) ⋅ 点赞:(0)

作者使用HMRouter,搭建鸿蒙三层架构完成App时候,在登录页进入首页的时候遇到了一个Bug,使用Router跳转后,在HMRouter中无法跳转页面了,现在将该bug的解决方法分享出来。

错误示例代码如下:

import { router } from '@kit.ArkUI';

@Entry
@ComponentV2
struct LoginPage {
  @State message: string = 'Hello World';
  aboutToAppear(): void {
    console.log('LifeCircle创建')
  }
  onDidBuild(): void {
    console.log('LifeCircle组件构建完成')
  }
  onPageShow(): void {
    console.log('页面-PageShow')
  }
  onPageHide(): void {
    console.log('页面-Page隐藏')
  }
  build() {
    Column(){
        /*登录页面代码省略**/
    }
    .onVisibleAreaChange([1.0],()=>{
        /**省略登录校验过程**/
      router.replaceUrl({url:'pages/Index'})
    })
  }
}

作者为了方便,直接在onVisibleAreaChange中直接登录跳转到首页去了,到了首页发现,使用HMRouter无法跳转到其他页面了。

分析错误原因:

onVisibleAreaChange 是高频触发的回调,若在此处直接跳转,可能因页面未完全初始化导致路由状态异常。(页面生命周期冲突)

解决方案:

避免在 onVisibleAreaChange 中直接跳转,改用显式触发(如按钮点击)或页面生命周期回调

例如下面示例代码

import { router } from '@kit.ArkUI';

@Entry
@Component
struct LoginPage{
  @State message: string = 'Hello World';
  aboutToAppear(): void {
    router.replaceUrl({url:'pages/Index'})
    console.log('LifeCircle创建')
  }
  onDidBuild(): void {
    console.log('LifeCircle组件构建完成')
  }
  onPageShow(): void {
    console.log('页面-PageShow')
  }
  onPageHide(): void {
    console.log('页面-Page隐藏')
  }
  build() {
    Column(){
    }
  }
}

在aboutToAppear中,进行页面跳转即可。

实际结果:在页面生命周期回调中跳转到首页后,HMRouter,可以正常跳转页面。Bug修改成功


网站公告

今日签到

点亮在社区的每一天
去签到