DEV Community

xiaoyao-yao
xiaoyao-yao

Posted on • Edited on

HarmonyOS NEXT-HMRouter, the problem cannot be jumped after using router


The author uses a third-party library @HMRouter to build a three-layer architecture (basic feature layer, product customization layer, and public capability layer) of HarmonyOS to complete the App, and when the cross-package jump is made, a strange bug is encountered when the login page enters the home page, after we use router.push() to jump, and then use HMRouter to jump to the page suddenly, so what should we do? , and now share the solution to the bug.

The sample error code looks like this:

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

@Entry
@ComponentV2
struct LoginPage {
@State message: string = 'Hello World';
aboutToAppear(): void {
console.log('LifeCircle creation')
}
onDidBuild(): void {
console.log('The LifeCircle component is built')
}
onPageShow(): void {
console.log('PageShow')
}
onPageHide(): void {
console.log('Page - Page hidden')
}
build() {
Column(){
/The login page code is omitted/
}
.onVisibleAreaChange([1.0],()=>{
/
Omit the login verification process*/
router.replaceUrl({url:'pages/Index'})
})
}
}

For the sake of convenience, when the author has logged in, he directly logged in to onVisibleAreaChange and jumped to the home page, and found that he couldn't jump to other pages using HMRouter, and there was no response when he clicked the jump button.

Analyze the cause of the error:

onVisibleAreaChange is a high-frequency triggered callback, if you jump directly here, the route status may be abnormal because the page is not fully initialized. (Page Lifecycle Conflict)

Solution:

Avoid jumping directly in onVisibleAreaChange and instead use explicit triggers (such as button clicks) or page lifecycle callbacks

For example, the following example code shows:

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

@Entry
@Component
struct LoginPage{
@State message: string = 'Hello World';
aboutToAppear(): void {
router.replaceUrl({url:'pages/Index'})
console.log('LifeCircle creation')
}
onDidBuild(): void {
console.log('The LifeCircle component is built')
}
onPageShow(): void {
console.log('PageShow')
}
onPageHide(): void {
console.log('Page - Page hidden')
}
build() {
Column(){
}
}
}

In aboutToAppear, just redirect to our page.

Actual result: After jumping to the homepage in the page lifecycle callback, HMRouter can jump to the page normally. The bug was successfully fixed.

Top comments (0)