
一、案例介绍
本案例将展示如何使用NavDestination组件实现一个具有完整生命周期管理的页面导航系统。通过本案例,您将学习NavDestination组件的基础用法和生命周期管理的最佳实践。
二、实现效果
- 基础页面导航
- 生命周期管理
- 数据加载状态
- 页面状态维护
三、代码实现
1. 定义数据结构
type PageState = {
isLoading: boolean
data: string[]
currentIndex: number
}
@Entry
@Component
struct LifecycleExample {
@State pageState: PageState = {
isLoading: true,
data: [],
currentIndex: 0
}
build() {
Column() {
this.NavigationContent()
}
.width('100%')
.height('100%')
.backgroundColor('#F5F5F5')
}
}
2. 实现导航容器
@Builder
private NavigationContent() {
Navigation() {
NavRouter() {
Column() {
Text('进入详情页面')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.padding(12)
.margin(8)
.backgroundColor(Color.White)
.borderRadius(8)
}
.width('100%')
.padding({ top: 20, bottom: 20 })
NavDestination() {
this.DetailContent()
}
.title('详情页面')
.onShown(() => {
this.loadPageData()
})
.onHidden(() => {
this.clearPageState()
})
.onBackPressed(() => {
return this.handleBackPress()
})
}
}
.title('生命周期示例')
.titleMode(NavigationTitleMode.Full)
.mode(NavigationMode.Stack)
}
3. 实现详情页面内容
@Builder
private DetailContent() {
Column() {
if (this.pageState.isLoading) {
this.LoadingView()
} else {
this.ContentView()
}
}
.width('100%')
.height('100%')
}
@Builder
private LoadingView() {
Column() {
LoadingProgress()
.width(50)
.height(50)
Text('加载中...')
.fontSize(14)
.fontColor('#999999')
.margin({ top: 12 })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
@Builder
private ContentView() {
Column() {
List({ space: 12 }) {
ForEach(this.pageState.data, (item: string, index: number) => {
ListItem() {
this.ContentItem(item, index)
}
})
}
.width('100%')
.padding(16)
}
.width('100%')
.height('100%')
}
4. 实现列表项组件
@Builder
private ContentItem(item: string, index: number) {
Column() {
Text(item)
.fontSize(16)
.fontColor('#333333')
.padding(16)
if (index === this.pageState.currentIndex) {
Text('当前选中')
.fontSize(12)
.fontColor('#007DFF')
.margin({ top: 4 })
}
}
.width('100%')
.backgroundColor(Color.White)
.borderRadius(8)
.onClick(() => {
this.pageState.currentIndex = index
})
}
5. 实现数据和状态管理
private loadPageData() {
this.pageState.isLoading = true
// 模拟异步数据加载
setTimeout(() => {
this.pageState.data = [
'项目 1',
'项目 2',
'项目 3',
'项目 4',
'项目 5'
]
this.pageState.isLoading = false
}, 2000)
}
private clearPageState() {
this.pageState = {
isLoading: true,
data: [],
currentIndex: 0
}
}
private handleBackPress(): boolean {
if (this.pageState.isLoading) {
return false
}
if (this.pageState.currentIndex !== 0) {
AlertDialog.show({
title: '提示',
message: '当前有选中项,确定要返回吗?',
primaryButton: {
value: '确定',
action: () => {
return true
}
},
secondaryButton: {
value: '取消',
action: () => {
return false
}
}
})
return false
}
return true
}
四、总结
本案例通过使用 NavDestination 组件实现了一个具有完整生命周期管理的页面导航系统。通过定义数据结构和状态管理逻辑,展示了如何在页面显示(onShown)、隐藏(onHidden)和返回(onBackPressed)时进行数据加载、状态清理和交互处理。同时,通过加载状态的动态展示和内容的按需加载,优化了用户体验。这种基础用法和生命周期管理的最佳实践适用于需要高效管理页面状态和数据的导航场景。
557

被折叠的 条评论
为什么被折叠?



