Skip to content

生命周期管理

理解不同组件的生命周期管理策略,以及生命周期感知的最佳实践。


1. 各组件生命周期总览

Application 层级:
├── onCreate → onDestroy(应用级)
└── onWindowStageCreate/Destroy(窗口级)

UIAbility 层级:
├── onCreate → onDestroy
├── onWindowStageCreate/Destroy
├── onForeground(前台)
└── onBackground(后台)

页面组件(@Entry):
├── aboutToAppear → aboutToDisappear
├── onPageShow → onPageHide
└── onBackPress

子组件:
├── aboutToAppear → aboutToDisappear
└── build(状态变化时重复执行)

2. 生命周期管理策略

2.1 Application 生命周期管理

typescript
// Application 级资源管理
class MyApp extends UIAbility {
    // 应用级资源
    private globalStore: GlobalStore | null = null
    private eventSubscriptions: Array<() => void> = []

    onCreate(): void {
        // 1. 初始化全局 Store
        this.globalStore = new GlobalStore()
        
        // 2. 订阅系统事件
        let sub = context.getApplicationContext().commonEventManager.subscribe({
            actionList: ['system.power.battery.low', 'system.network.change']
        })
        this.eventSubscriptions.push(() => this.unsubscribe(sub))
    }

    onDestroy(): void {
        // 清理所有订阅
        for (let unsub of this.eventSubscriptions) {
            unsub()
        }
        this.eventSubscriptions = []
        
        // 清理全局资源
        this.globalStore = null
    }
}

2.2 UIAbility 生命周期管理

typescript
class EntryAbility extends UIAbility {
    private isResumed: boolean = false
    private savedState: string = ''

    onCreate(): void {
        console.log('UIAbility onCreate')
    }

    onWindowStageCreate(windowStage: window.WindowStage): void {
        console.log('UIAbility onWindowStageCreate')
        windowStage.loadContent('pages/Index')
    }

    onForeground(): void {
        console.log('UIAbility onForeground - 回到前台')
        // 刷新数据、恢复任务
        this.isResumed = true
    }

    onBackground(): void {
        console.log('UIAbility onBackground - 进入后台')
        // 保存状态、暂停任务
        this.isResumed = false
        this.savedState = JSON.stringify({ timestamp: Date.now() })
    }

    onWindowStageDestroy(): void {
        console.log('UIAbility onWindowStageDestroy')
    }

    onDestroy(): void {
        console.log('UIAbility onDestroy')
    }
}

3. 生命周期感知组件

3.1 页面级生命周期管理

typescript
@Entry
@Component
struct Index {
    @State data: string = ''
    private refreshTimer: number = -1

    // 页面创建
    onPageShow() {
        console.log('页面显示,刷新数据')
        this.refreshTimer = setInterval(() => {
            this.data = new Date().toLocaleTimeString()
        }, 1000)
    }

    // 页面隐藏
    onPageHide() {
        console.log('页面隐藏,暂停定时任务')
        if (this.refreshTimer >= 0) {
            clearInterval(this.refreshTimer)
            this.refreshTimer = -1
        }
    }

    // 返回处理
    onBackPress() {
        console.log('返回按钮被点击')
        return false  // false = 不拦截,true = 拦截
    }

    build() {
        Text(this.data).fontSize(32fp)
    }
}

4. 生命周期陷阱

4.1 内存泄漏

typescript
@Component
struct MyComponent {
    private timerId: number = -1

    aboutToAppear() {
        // ✅ 正确:定时器在 aboutToDisappear 中清理
        this.timerId = setInterval(() => {
            console.log('定时任务')
        }, 1000)
    }

    aboutToDisappear() {
        // ✅ 清理定时器
        if (this.timerId >= 0) {
            clearInterval(this.timerId)
        }
    }

    build() {
        Text('内容')
    }
}

4.2 重复订阅

typescript
// ❌ 错误:每次 onPageShow 都订阅,导致重复
@Entry
@Component
struct Index {
    onPageShow() {
        // 每次页面显示都订阅 → 重复!
        context.commonEventManager.subscribe({ ... })
    }
}

// ✅ 正确:只在 aboutToAppear 中订阅一次
@Entry
@Component
struct Index {
    aboutToAppear() {
        context.commonEventManager.subscribe({ ... })
    }
    
    aboutToDisappear() {
        context.commonEventManager.unsubscribe({ ... })
    }
}

5. 生命周期状态机

UIAbility 状态转换:

    onCreate


onWindowStageCreate


   onForeground ◄──────────┐
       │                   │
       ▼                   │
   onBackground ──────────┘


onWindowStageDestroy


   onDestroy

6. 面试高频考点

Q1: 生命周期管理的关键点?

回答:在适当生命周期初始化/清理资源,避免内存泄漏;页面级 onPageShow/onPageHide 控制任务启停;子组件 aboutToAppear/aboutToDisappear 管理资源。

Q2: 生命周期感知组件如何处理数据刷新?

回答:在 onPageShow 中刷新数据,onPageHide 中暂停定时任务;在 onForeground/onBackground 中控制 UIAbility 级任务。


🐱 小猫提示:生命周期管理记住 "onPageShow 刷新、onPageHide 暂停、aboutToDisappear 清理"。内存泄漏是高频考点。