HarmonyOS鸿蒙Next中如何解决Navigation路由调用pop后onPop回调代码不执行的问题
HarmonyOS鸿蒙Next中如何解决Navigation路由调用pop后onPop回调代码不执行的问题
【问题现象】
使用Navigaon构建页面路由,从pageOne通过pushPath方法跳转到pageTwo,并期望通过onPop回调接收入栈页面(即pageTwo)出栈时的返回结果,预期从pageTwo返回时pageOne的onPop能接收到回调事件,实际未接收到回调事件。问题现象如下图:
【定位思路】
示意图如下:
问题代码如下:
// PageOne.ets
class ParamWithOp {
operation: number = 1
count: number = 10
}
@Builder
export function PageOneBuilder(name: string, param: Object) {
PageOne()
}
@Component
export struct PageOne {
pageInfo: NavPathStack = new NavPathStack();
@State message: string = 'Hello World'
build() {
NavDestination() {
Column() {
Text(this.message)
.width('80%')
.height(50)
.margin(10)
Button('pushPath', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(10)
.onClick(()=>{
// 将name指定的NavDestination页面信息入栈,传递的数据为param,添加接收处理结果的onPop回调。
this.pageInfo.pushPath({name: 'pageTwo', param: new ParamWithOp(), onPop: (popInfo: PopInfo)=>{
this.message = '[pushPath]last page is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result);
}});
})
}.width('100%').height('100%')
}.title('pageOne')
}
}
// PageTwo.ets
class resultClass {
constructor(count: number) {
this.count = count;
}
count: number = 10
}
@Builder
export function PageTwoBuilder() {
PageTwo()
}
@Component
export struct PageTwo {
pathStack: NavPathStack = new NavPathStack()
build() {
NavDestination() {
Column() {
Button('pop', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
// 回退到上一个页面,此处代码,在pop回pageOne页面时,未传参数
this.pathStack.pop();
})
}.width('100%').height('100%')
}.title('pageTwo')
.onReady((context: NavDestinationContext) => {
this.pathStack = context.pathStack
})
}
}
查看官方文档 pushPathByName,关于onPop方法有明确的说明:Callback回调,用于页面出栈时触发该回调处理返回结果,仅pop中设置result参数后触发。
但是对于pushPath方法的NavPathInfo入参,其中的onPop未明确说明需要设置result参数后才能触发,实际上,对于pushPath方法注册的onPop回调,也需要在调用pop方法时,指定result参数,否则无法成功执行onPop回调。
【解决方案】
按上节所述,修改方法为在pageTwo中调用pop方法时,传入result参数,即可在pageOne中成功收到onPop的回调。
代码示例如下:
// PageTwo.ets
Button('pop')
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
// 回退到上一个页面,将处理结果传入push的onPop回调中。
this.pathStack.pop(new resultClass(1));
})
修改后的运行效果如下图,可以看到,当pageTwo在onPop时,传入了result参数,在pageOne成功执行了onPop回调,并接收到相关参数。
【总结】
对于Navigation组件中使用pushPath方法,如果希望能够成功收到onPop的回调,需要在pop时传入result参数。
更多关于HarmonyOS鸿蒙Next中如何解决Navigation路由调用pop后onPop回调代码不执行的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS鸿蒙Next中如何解决Navigation路由调用pop后onPop回调代码不执行的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,使用pushPath
方法时,若希望onPop
回调能成功执行,需在调用pop
方法时传入result
参数。具体修改如下:
// PageTwo.ets
Button('pop')
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.pathStack.pop(new resultClass(1));
})
修改后,pageOne
将成功接收到onPop
回调并处理返回结果。