在router.pushUrl的回调中执行router.clear会崩溃。
router.pushUrl({ url: "login/UserNameLoginPage" }, () => { router.clear() })
报错Log信息如下:
Error name:Error Error message:Internal error. UI execution context not found. Error code:100001
全局的UI接口是和具体UI实例的执行上下文相关的,在当前接口调用时,通过追溯调用链跟踪到UI的上下文,来确定具体的UI实例。若在非UI页面中或者一些异步回调中调用这类接口,可能无法跟踪到当前UI的上下文,导致接口执行失败。和上下文相关的全局接口请查阅@ohos.arkui.UIContext模块。
@Entry @Component struct RouterDemo { aboutToAppear(): void { // 获取UIContext,保存在AppStorage中 // 也可以在EntryAbility.ets的onWindowStageCreate方法中保存UIContext AppStorage.setOrCreate('UIContext', this.getUIContext()); } build() { Column() { Button('跳转页面') .onClick(() => { Auth.gotoLoginPage(); }); }.height('100%').width('100%'); } } class Auth { // 跳转到登录页 static gotoLoginPage() { // 通过AppStorage获取UIContext const uiContext = AppStorage.get<UIContext>('UIContext'); if (uiContext) { uiContext.getRouter().pushUrl({ url: 'pages/Index' // 需自行创建一个Index页面 }); } } }