阅读量:0
官方文档:页面和自定义组件生命周期
目录标题
组件生命周期
被@Component
装饰的组件便可以调用组件的生命周期
。
aboutToAppear
:实例创建后,在执行其build()
函数之前执行。onDidBuild
:组件build()
函数执行完成之后回调该接口。aboutToDisappear
:实例销毁前。
创建实例 → aboutToAppear
→ build()
→ onDidBuild
→ … → aboutToDisappear
→ 实例销毁
页面生命周期
只有被@Entry
装饰的组件才可以调用页面的生命周期
。
onPageShow
:页面显示时执行onPageHide
:页面隐藏时执行onBackPress
:点击返回键执行
练习中理解
FirstPage.ets
import { router } from '@kit.ArkUI' @Entry @Component struct FirstPage { @State message: string = 'First Page'; build() { Row() { Column() { Text(this.message).fontSize(50).fontWeight(FontWeight.Bold) Button('Next') .onClick(() => { router.pushUrl({ url: "pages/SecondPage" }) }) } .width('100%') } .height('100%') } aboutToAppear(): void { console.log("FirstPage----------aboutToAppear1") } aboutToDisappear(): void { console.log("FirstPage----------aboutToDisappear1") } onPageShow(): void { console.log("FirstPage----------onPageShow1") } onPageHide(): void { console.log("FirstPage----------onPageHide1") } onBackPress(): boolean | void { console.log("FirstPage----------onBackPress1") } }
SecondPage.ets
import { router } from '@kit.ArkUI' @Entry @Component struct SecondPage { @State message: string = 'Second Page'; build() { Row() { Column() { Text(this.message).fontSize(50).fontWeight(FontWeight.Bold) Button("Back") .onClick(() => { router.back() }) } .width('100%') } .height('100%') } aboutToAppear(): void { console.log("FirstPage----------aboutToAppear2") } aboutToDisappear(): void { console.log("FirstPage----------aboutToDisappear2") } onPageShow(): void { console.log("FirstPage----------onPageShow2") } onPageHide(): void { console.log("FirstPage----------onPageHide2") } onBackPress(): boolean | void { console.log("FirstPage----------onBackPress2") } }
第1步:加载 First Page
app Log: FirstPage----------aboutToAppear1 app Log: FirstPage----------onPageShow1
第2步:First Page → 点Next按钮
app Log: FirstPage----------onPageHide1 app Log: FirstPage----------aboutToAppear2 app Log: FirstPage----------onPageShow2
第3步:Second Page → 点back按钮
app Log: FirstPage----------onPageHide2 app Log: FirstPage----------onPageShow1 app Log: FirstPage----------aboutToDisappear2
第4步:First Page → 点Next按钮
app Log: FirstPage----------onPageHide1 app Log: FirstPage----------aboutToAppear2 app Log: FirstPage----------onPageShow2
第5步:Second Page → 点返回按钮
app Log: FirstPage----------onBackPress2 app Log: FirstPage----------onPageHide2 app Log: FirstPage----------onPageShow1 app Log: FirstPage----------aboutToDisappear2