HarmonyOS鸿蒙Next中Navigation做为闪屏页时,不能移除页面栈吗?
HarmonyOS鸿蒙Next中Navigation做为闪屏页时,不能移除页面栈吗? 如下代码是我的闪屏页,使用了replacePath跳转,但是并没有把这个闪屏页移除页面栈,请问这种情况怎么办?
@Entry
@Component
struct SplashPage {
pageInfo: NavPathStack = new NavPathStack();
@State duration: number = 3;
private intervalId: number = -1
aboutToAppear(): void {
this.intervalId = setInterval(() => {
if (this.duration > 0) {
this.duration -= 1
} else {
this.startPage()
}
}, 1000)
}
build() {
Navigation(this.pageInfo) {
Column() {
Text('我是闪屏页')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.backgroundColor('#C0C0C0')
}.hideTitleBar(true).title('NavIndex')
}
private startPage() {
clearInterval(this.intervalId)
this.pageInfo.replacePath({ name: 'LoginPage' }); // 将name指定的NavDestination页面-替换页面栈操作
}
}
如下代码是登录页面
@Builder
export function LoginPageBuilder(name: string, param: Object) {
LoginPage()
}
@Component
export struct LoginPage {
pageInfo?: NavPathStack
build() {
NavDestination() {
Column() {
Text('欢迎使用APP,我是登录页面')
.fontColor('#E0000000')
.fontSize(27)
.fontWeight(600)
.width('100%')
.textAlign(TextAlign.Center)
.margin({ left: 16 })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.title('LoginPage')
.hideTitleBar(true)
.onReady((context: NavDestinationContext) => {
this.pageInfo = context.pathStack;
})
// .onBackPressed(() => {
// this.pageInfo.pop({ number: 1 }); // 弹出路由栈栈顶元素。
// return true;
// })
}
}
需要添加的navigation的路由配置如下:
;
@State duration: number = 3;
private intervalId: number = -1;
@State hideFlag: boolean = false;
aboutToAppear(): void {
this.intervalId = setInterval(() => {
if (this.duration > 0) {
this.duration -= 1;
} else {
this.hideFlag = false;
this.startPage()
}
}, 1000)
}
build() {
Navigation(this.pageInfo) {
Column() {
Text('我是闪屏页')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.backgroundColor('#C0C0C0')
}.hideTitleBar(true).title('NavIndex').hideNavBar(this.hideFlag)
}
private startPage() {
clearInterval(this.intervalId)
this.pageInfo.replacePath({ name: 'LoginPage' }); // 将name指定的NavDestination页面-替换页面栈操作
}
}
触发物理返回键的时候,还是会回到闪屏页~,
在HarmonyOS鸿蒙Next中,使用Navigation作为闪屏页时,默认情况下页面栈会被保留。若需移除页面栈,可通过router.clear()
方法清除页面栈,确保闪屏页后跳转的页面为唯一页面。具体实现需在闪屏页跳转前调用该方法。
在HarmonyOS Next中,使用Navigation作为闪屏页时,replacePath
确实不会完全移除页面栈。这是因为Navigation组件本身会维护一个页面栈结构,即使使用replacePath
替换当前页面,Navigation的栈结构仍然会保留。
针对闪屏页场景,建议采用以下两种解决方案:
- 使用Router模块替代Navigation:
import router from '@ohos.router';
private startPage() {
clearInterval(this.intervalId);
router.replaceUrl({ url: 'pages/LoginPage' });
}
- 如果必须使用Navigation,可以在跳转后手动清除栈:
private startPage() {
clearInterval(this.intervalId);
this.pageInfo.replacePath({ name: 'LoginPage' });
// 延迟执行确保页面跳转完成
setTimeout(() => {
this.pageInfo.pop({ number: 1 });
}, 100);
}
注意:第二种方案可能会引起短暂的白屏现象,第一种方案是更推荐的实现方式。