目录

自定义组件生命周期(推荐)

概述

已有的自定义组件生命周期回调函数触发只取决于事件的触发,在某些特定的情况下,会出现自定义组件生命周期回调函数的触发顺序不符合预期。比如:aboutToDisappear在特定情况下会误调用aboutToAppear、组件未展开被复用时,会误调用aboutToReuse。新的自定义组件生命周期回调函数受状态机限制,生命周期回调函数调用时机符合预期。

自定义组件生命周期,即用@Component或@ComponentV2装饰的自定义组件的生命周期,从API version 23开始,提供以下生命周期装饰器:

自定义组件生命周期受状态机限制,每个生命周期回调函数仅在特定的状态转换阶段才会被调用,比如@ComponentReuse的限制条件是从CustomComponentLifecycleState.RECYCLED到CustomComponentLifecycleState.BUILT阶段触发,@ComponentAppear仅在组件处于CustomComponentLifecycleState.INIT状态时触发,流程如下图所示。

[h2]自定义组件的创建和渲染流程

  1. 自定义组件的创建:自定义组件的实例由ArkUI框架创建。

  2. 初始化自定义组件的成员变量:通过本地默认值或者构造函数传递参数来初始化自定义组件的成员变量,初始化顺序为成员变量的定义顺序。

  3. 在首次渲染的时候,执行build函数渲染系统组件,如果子组件为自定义组件,则创建自定义组件的实例。在首次渲染的过程中,框架会记录状态变量和组件的映射关系,当状态变量改变时,驱动其相关的组件刷新。

[h2]自定义组件的删除

例如if组件的分支改变或ForEach循环渲染中数组的个数改变,组件将被移除:

  1. 在删除组件之前,将调用其@ComponentDisappear装饰的生命周期函数,标记着该节点将要被销毁。ArkUI的节点删除机制是:后端节点直接从组件树上摘下,后端节点被销毁,对前端节点解引用,前端节点已经没有引用时,将被Ark虚拟机垃圾回收。

  2. 自定义组件和它的变量将被删除,如果组件有同步的变量(如@Link、@Prop、@StorageLink),将从状态数据源上取消注册。

自定义组件的激活与非激活生命周期

自定义组件生命周期装饰器@ComponentActive和@ComponentInactive自API版本26.0.0起可用,用于监听组件的激活状态变化,不受状态机约束。

当组件由非激活转为激活状态时(例如应用从后台切回前台、页面重新显示时),会触发@ComponentActive装饰的函数;反之,当组件从激活转为非激活状态时(例如应用退至后台、页面隐藏或组件预创建时),则调用@ComponentInactive装饰的函数。组件激活/非激活并不等同于其可见性。

本文档中,组件转变为激活态指自定义组件从非激活状态转变为激活状态,触发@ComponentActive;组件转变为非激活态指自定义组件从激活状态转变为非激活状态,并触发@ComponentInactive。

目前激活和非激活生命周期支持下述场景。

[h2]组件回收复用场景下监听激活状态变化

进入复用池的组件转变为非激活态。可复用组件从复用池中重新添加到节点树时转变为激活态。本示例展示了组件回收复用场景下,自定义组件激活和非激活生命周期回调函数触发情况。

import { ComponentActive, ComponentInactive, ComponentReuse, ComponentRecycle } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  @State changeChild: boolean = false;

  build() {
    Column() {
      Button('change')
        .margin(10)
        .onClick(() => {
          // 切换Child组件的显示状态,触发组件的回收或复用
          this.changeChild = !this.changeChild;
        })
      if (this.changeChild) {
        Child()
      }
    }
    .width('100%')
  }
}

@Reusable
@Component
struct Child {

  @ComponentReuse
  myReuse() {
    // 组件复用时触发
    console.info(`Child myReuse`);
  }

  aboutToReuse() {
    // 组件复用时触发
    console.info(`Child aboutToReuse`);
  }

  @ComponentActive
  myActive() {
    // 组件从非激活状态变为激活状态时触发
    console.info(`Child myActive`);
  }

  @ComponentRecycle
  myRecycle() {
    // 组件进入复用池时触发
    console.info(`Child myRecycle`);
  }

  aboutToRecycle() {
    // 组件进入复用池时触发
    console.info(`Child aboutToRecycle`);
  }

  @ComponentInactive
  myInactive() {
    // 组件从激活状态变为非激活状态时触发
    console.info(`Child myInactive`);
  }

  build() {
    Text('Child')
  }
}

上述代码建议按以下步骤执行。

  1. 点击change,Child组件第一次创建。

  2. 点击change,Child组件触发@ComponentInactive装饰的函数和回收事件。

    Child myInactive
    Child aboutToRecycle
    Child myRecycle
  3. 点击change,Child组件触发复用事件和@ComponentActive装饰的函数。

    Child aboutToReuse
    Child myReuse
    Child myActive

当开发者同时使用回收复用和激活生命周期时,自定义组件触发相关组件的时序有以下约束:@ComponentInactive触发时机早于@ComponentRecycle和aboutToRecycle,@ComponentActive触发时机晚于@ComponentReuse和aboutToReuse。

[h2]懒创建场景下监听激活状态变化

懒创建的含义为,容器中有多个组件,只有选定的组件完成创建,其余组件需要通过翻页跳转等方法选中时触发创建。当切换到创建完成的组件时,该组件转变为激活态;组件不再被选中时,该组件转变为非激活态。

懒创建场景包含Tabs和Navigation,以下示例展示Navigation和Tabs场景中,@ComponentActive和@ComponentInactive生命周期装饰器的触发时机。

// Index.ets
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State pageStack: NavPathStack = new NavPathStack();

  build() {
    Column() {
      Navigation(this.pageStack) {
        Text(this.message)
          .margin(10)
        Button(`PageOne`)
          .margin(10)
          .onClick(() => {
            // 跳转到PageOne页面
            this.pageStack.pushPath({ name: 'PageOne' });
          })
          .width('40%')
        Button(`PageTwo`)
          .margin(10)
          .onClick(() => {
            // 跳转到PageTwo页面
            this.pageStack.pushPath({ name: 'PageTwo' });
          })
          .width('40%')
      }
    }
  }
}
@Builder
export function PageOneBuilder() {
  PageOne()
}

@Entry
@Component
struct PageOne {
  @State pageStack: NavPathStack = new NavPathStack();

  build() {
    NavDestination() {
      Column() {
        Text(`PageOne`)
          .margin(10)
        Button('PageTwo')
          .margin(10)
          .onClick(() => {
            // 跳转到PageTwo页面
            this.pageStack.pushPath({ name: 'PageTwo' });
          })
          .width('40%')
        Button(`back`)
          .margin(10)
          .onClick(() => {
            // 返回上一页
            this.pageStack.pop();
          })
          .width('40%')
      }
    }
    .onReady((context: NavDestinationContext) => {
      // 页面准备就绪时,获取导航路径栈
      this.pageStack = context.pathStack;
    })
  }
}
import { ComponentActive, ComponentInactive } from '@kit.ArkUI';

@Builder
export function PageTwoBuilder() {
  PageTwo()
}

@Entry
@Component
struct PageTwo {
  @State pageStack: NavPathStack = new NavPathStack();

  build() {
    NavDestination() {
      Column() {
        Text(`PageTwo`)
          .margin(10)
        Button(`PageOne`)
          .margin(10)
          .onClick(() => {
            // 跳转到PageOne页面
            this.pageStack.pushPath({ name: 'PageOne' });
          })
          .width('40%')
        Button(`back`)
          .margin(10)
          .onClick(() => {
            // 返回上一页
            this.pageStack.pop();
          })
          .width('40%')
        Row() {
          Column() {
            TabsComponent();
          }
          .width('100%')
        }
        .margin(10)
      }
    }
    .onReady((context: NavDestinationContext) => {
      // 页面准备就绪时,获取导航路径栈
      this.pageStack = context.pathStack;
    })
  }
}

// 冻结子组件:使用freezeWhenInactive配置
@Component({ freezeWhenInactive: true })
struct FreezeChild {
  @Link message: number;
  index: number = 0;

  @ComponentActive
  myActive() {
    // 组件从非激活状态变为激活状态时触发
    console.info(`FreezeChild myActive, index: ${this.index}`);
  }

  @ComponentInactive
  myInactive() {
    // 组件从激活状态变为非激活状态时触发
    console.info(`FreezeChild myInactive, index: ${this.index}`);
  }

  build() {
    Text(`message ${this.message}, index: ${this.index}`)
  }
}

@Component
struct TabsComponent {
  private data: number[] = [0, 1, 2];
  @State @Watch('onMessageUpdated') message: number = 0;

  onMessageUpdated() {
    console.info(`TabContent message callback func ${this.message}`);
  }

  build() {
    Column() {
      Button(`Incr state ${this.message}`)
        .onClick(() => {
          // 点击Button修改message,触发可见TabContent的onMessageUpdated回调
          this.message++;
        })
        .margin(10)
      Tabs() {
        ForEach(this.data, (item: number) => {
          TabContent() {
            // 将message作为@Link传递给FreezeChild,使状态可以在父子组件间同步
            FreezeChild({ message: this.message, index: item })
          }.tabBar(`tab${item}`)
        }, (item: number) => item.toString())
      }
      .vertical(false)
      .scrollable(true)
      .barMode(BarMode.Fixed)
      .barWidth(400)
      .barHeight(50)
      .animationDuration(400)
      .width('100%')
      .height(200)
      .backgroundColor(0xF5F5F5)
    }
  }
}

在系统配置文件route_map.json中配置子页信息如下:

{
  "routerMap": [
    {
      "name": "PageOne",
      "buildFunction": "PageOneBuilder",
      "pageSourceFile": "src/main/ets/pages/PageOne.ets"
    },
    {
      "name": "PageTwo",
      "buildFunction": "PageTwoBuilder",
      "pageSourceFile": "src/main/ets/pages/PageTwo.ets"
    }
  ]
}

在module.json5配置文件中配置routerMap路由映射。

{
  "module": {
    // ···
    "routerMap": "$profile:route_map",
    // ···
  }
}

场景说明与日志输出:

本示例展示了Navigation页面路由和TabContent切换场景下的组件激活/非激活状态变化。当页面路由切换时,离开页面的FreezeChild触发@ComponentInactive,返回时触发@ComponentActive。

上述代码建议按以下步骤执行。

  1. 点击PageTwo按钮,页面跳转到PageTwo。

    tab0被选中,tab0中的FreezeChild组件完成创建。

  2. 点击tab1,tab0不再被选中并转变为非激活态,tab0中的FreezeChild触发@ComponentInactive。

    FreezeChild myInactive, index: 0
  3. 点击tab0,tab0被选中并转变为激活态,tab0中的FreezeChild触发@ComponentActive。tab1不再被选中并转变为非激活态,tab1中的FreezeChild触发@ComponentInactive。

    FreezeChild myActive, index: 0
    FreezeChild myInactive, index: 1
  4. 点击PageOne,页面跳转到PageOne。PageTwo中的tab0不再被选中并转变为非激活态,tab0中的FreezeChild触发@ComponentInactive。

    FreezeChild myInactive, index: 0
  5. 点击back,页面跳转回PageTwo。PageTwo中的tab0被选中并转变为激活态,tab0中的FreezeChild触发@ComponentActive。

    FreezeChild myActive, index: 0

[h2]预加载场景下监听激活状态变化

以LazyForEach为例,LazyForEach预加载区域的组件创建完毕转变为非激活态。List、Swiper、Grid、WaterFlow等组件使用LazyForEach时,可以通过cachedCount的count属性设置预加载区域的节点数量。

本示例展示了List和LazyForEach场景下的组件激活/非激活状态变化。

import { ComponentActive, ComponentInactive } from '@kit.ArkUI';
import { MyDataSource } from './BasicDataSource';

@Entry
@Component
struct Index {
  @State dataSource: MyDataSource<string> = new MyDataSource();
  @State colors: number[] = [0xFFC0CB, 0xDA70D6, 0x6B8E23, 0x6A5ACD, 0x00FFFF, 0x00FF7F];
  @State changeShow: boolean = false;

  aboutToAppear(): void {
    for (let index = 1; index <= 50; index++) {
      this.dataSource.pushData('page - ' + index);
    }
  }

  build() {
    Column() {
      Button('change')
        .margin(10)
        .onClick(() => {
          // 控制List的创建和销毁
          this.changeShow = !this.changeShow;
        })
      if (this.changeShow) {
        List({ space: 10 }) {
          LazyForEach(this.dataSource, (item: string, index: number) => {
            ListItem() {
              Child({ item: item.toString(), index: index.toString() })
            }
            .backgroundColor(Color.Pink)
            .width('100%')
            .height('15%')
          }, (item: string) => item.toString())
        }
        .width('80%')
        .height('60%')
        // 预加载区域可容纳节点数量为5
        .cachedCount(5, false)
      }
    }
    .width('100%')
  }
}

@Component
struct Child {
  @State index: string = '';
  @State item: string = '';
  @ComponentActive
  myActive() {
    // 组件从非激活状态变为激活状态时触发
    console.info(`Child myActive, index: ${this.index}`);
  }
  @ComponentInactive
  myInactive() {
    // 组件从激活状态变为非激活状态时触发
    console.info(`Child myInactive, index: ${this.index}`);
  }
  build() {
    Column() {
      Text(`Item ${this.item}`)
    }
  }
}
abstract class BasicDataSource<T> implements IDataSource {
  private listeners: DataChangeListener[] = [];
  abstract totalCount(): number;
  abstract getData(index: number): T;

  // 注册改变数据的控制器
  registerDataChangeListener(listener: DataChangeListener): void {
    if (this.listeners.indexOf(listener) < 0) {
      this.listeners.push(listener);
    }
  }

  // 注销改变数据的控制器
  unregisterDataChangeListener(listener: DataChangeListener): void {
    const pos = this.listeners.indexOf(listener);
    if (pos >= 0) {
      this.listeners.splice(pos, 1);
    }
  }

  // 通知控制器数据增加
  notifyDataAdd(index: number): void {
    this.listeners.forEach(listener => {
      listener.onDataAdd(index);
    })
  }
}

export class MyDataSource<T> extends BasicDataSource<T> {
  private dataArray: T[] = [];

  // 数据源的数据总量
  public totalCount(): number {
    return this.dataArray.length;
  }

  // 返回指定索引位置的数据
  public getData(index: number): T {
    return this.dataArray[index];
  }

  // 添加一条数据
  public pushData(data: T): void {
    this.dataArray.push(data);
    this.notifyDataAdd(this.dataArray.length - 1);
  }
}

场景说明与日志输出:

上述代码建议按以下步骤执行。

  1. 点击change按钮,位于预加载区域的组件触发@ComponentInactive。

    Child myInactive, index: 6
    Child myInactive, index: 7
    Child myInactive, index: 8
    Child myInactive, index: 9
    Child myInactive, index: 10
  2. 向下滑动List,进入加载区域的组件触发@ComponentActive,进入预加载区域的组件触发@ComponentInactive,离开加载区域的组件触发@ComponentInactive。

    Child myActive, index: 6
    Child myInactive, index: 11
    Child myInactive, index: 0

当List的cachedCount的show属性设为true时,预加载节点创建完毕触发@ComponentInactive后,执行上树并触发@ComponentActive。

[h2]页面可见性变化场景下监听激活状态变化

Router页面每次隐藏时触发onPageHide,页面中的组件转变为非激活态;页面每次显示时触发onPageShow,页面中的组件转变为激活态。同理,亮屏时页面会触发onPageShow,页面中的组件转变为激活态;息屏时页面会触发onPageHide,页面中的组件转变为非激活态。

本示例展示了页面可见性变化场景下的组件激活/非激活状态变化。

import { ComponentActive, ComponentInactive } from '@kit.ArkUI';

@Entry
@Component
struct MyActiveSample {
  @State stateVar: string = 'Hello World';

  @ComponentActive
  myActive() {
    // 组件从非激活状态变为激活状态时触发
    console.info(`myActive`);
  }

  @ComponentInactive
  myInactive() {
    // 组件从激活状态变为非激活状态时触发
    console.info(`myInactive`);
  }

  build() {
    Column() {
      Text(this.stateVar)
    }
    .width(`100%`)
    .height(`100%`)
  }
}

场景说明与日志输出:

上述代码建议按以下步骤执行。

  1. 息屏,组件触发@ComponentInactive。

    myInactive
  2. 亮屏,组件触发@ComponentActive。

    myActive

限制条件

使用场景

[h2]自定义组件嵌套使用

通过以下示例,来详细说明自定义组件在嵌套使用时,自定义组件生命周期的调用时序:

import { hilog } from '@kit.PerformanceAnalysisKit';
import { ComponentAppear, ComponentBuilt, ComponentDisappear } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  @State show: boolean = true;
  @State btnColor: string = '#FF007DFF';
  build() {
    Column() {
      Button('delete Parent And Child')
        .margin(20)
        .width('60%')
        .backgroundColor(this.btnColor)
        .onClick(() => {
          this.show = !this.show;
        })
      if (this.show) {
        Parent()
      }
    }
    .width('100%')
  }
}
@Component
struct Parent {
  @State showChild: boolean = true;
  @State btnColor: string = '#FF007DFF';
  // 组件生命周期ComponentAppear,在Parent创建实例后,执行build函数之前回调myAppear
  @ComponentAppear
  myAppear() {
    hilog.info(0x0000, 'testTag', 'Parent myAppear');
  }
  // 组件生命周期ComponentBuilt,在Parent首次渲染触发的build函数执行完成之后回调myBuilt
  @ComponentBuilt
  myBuilt() {
    hilog.info(0x0000, 'testTag', 'Parent myBuilt');
  }
  // 组件生命周期ComponentDisappear,在Parent析构销毁之前回调myDisappear
  @ComponentDisappear
  myDisappear() {
    hilog.info(0x0000, 'testTag', 'Parent myDisappear');
  }

  build() {
    Column() {
      // this.showChild为true,创建Child子组件,执行Child myAppear
      if (this.showChild) {
        Child()
      }
      Button('delete Child')
        .width('60%')
        .margin(20)
        .backgroundColor(this.btnColor)
        .onClick(() => {
          // 更改this.showChild为false,删除Child子组件,执行Child myDisappear
          // 更改this.showChild为true,添加Child子组件,执行Child myAppear
          this.showChild = !this.showChild;
        })
    }
  }
}

@Component
struct Child {
  @State title: string = 'Hello World';
  @ComponentDisappear
  myDisappear() {
    hilog.info(0x0000, 'testTag', 'Child myDisappear');
  }
  @ComponentBuilt
  myBuilt() {
    hilog.info(0x0000, 'testTag', 'Child myBuilt');
  }
  @ComponentAppear
  myAppear() {
    hilog.info(0x0000, 'testTag', 'Child myAppear');
  }

  build() {
    Text(this.title)
      .fontSize(50)
      .margin(20)
      .onClick(() => {
        this.title = 'Hello ArkUI';
      })
  }
}

以上示例中,Index页面包含两个自定义组件,一个是Parent,一个是Child,Parent及其子组件Child分别声明了各自的自定义组件生命周期装饰器装饰的函数(myAppear / myBuilt / myDisappear)。

Parent myAppear
Parent myBuilt
Child myAppear
Child myBuilt
Parent myDisappear
Child myDisappear
Parent myAppear
Parent myBuilt
Child myAppear
Child myBuilt

当showChild为默认值true时,该示例的生命周期流程图如下所示:

[h2]自定义组件回收复用

通过以下示例,来详细说明自定义组件在使用时,回收复用的生命周期调用时序:

import { ComponentInit, ComponentAppear, ComponentBuilt, ComponentDisappear, ComponentReuse, ComponentRecycle } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

export class Message {
  public value: string | undefined;
  constructor(value: string) {
    this.value = value;
  }
}
@Entry
@Component
struct Index {
  @State changeChild: boolean = true;
  @State btnColor: string = '#FF007DFF';

  build() {
    Column() {
      Button(this.changeChild ? 'recycle child' : 'reuse child')
        .margin(20)
        .backgroundColor(this.btnColor)
        .width('50%')
        .onClick(() => {
          this.changeChild = !this.changeChild;
        })
      // 通过改变changeChild,实现Child的回收和复用
      // 更改this.changeChild为false,回收Child子组件,执行Child myRecycle
      // 更改this.changeChild为true,复用Child子组件,执行Child myReuse
      if (this.changeChild) {
        // 如果只有一个复用的组件,可以不用设置reuseId。
        Child({ message: new Message('child') })
          .reuseId('Child')
          .margin(10)
      }
    }
    .width('100%')
  }
}

@Reusable
@Component
struct Child {
  @State message: Message = new Message('Child');
  @State label: string = 'HelloWorld';
  @State changeGrandChild: boolean = true;
  @State btnColor: string = '#FF007DFF';
  @ComponentInit
  myInit() {
    hilog.info(0x0000, 'testTag', 'Child myInit');
  }
  @ComponentAppear
  myAppear() {
    this.label = 'myAppear';
    hilog.info(0x0000, 'testTag', 'Child myAppear');
  }
  @ComponentBuilt
  myBuilt() {
    this.label = 'myBuilt';
    hilog.info(0x0000, 'testTag', 'Child myBuilt');
  }
  @ComponentRecycle
  myRecycle() {
    this.label = 'myRecycle';
    hilog.info(0x0000, 'testTag', 'Child myRecycle');
  }
  @ComponentDisappear
  myDisappear() {
    this.label = 'myDisappear';
    hilog.info(0x0000, 'testTag', 'Child myDisappear');
  }
  @ComponentReuse
  myReuse(params?: Record<string, Object | undefined | null>) {
    this.label = 'myReuse';
    hilog.info(0x0000, 'testTag', 'Child myReuse');
  }

  build() {
    Column() {
      Text(this.message.value)
        .fontSize(30)
        .margin(10)
      Button(this.changeGrandChild ? 'recycle grandchild' : 'reuse grandchild')
        .width('50%')
        .margin(20)
        .backgroundColor(this.btnColor)
        .onClick(() => {
          this.changeGrandChild = !this.changeGrandChild;
        })
      if (this.changeGrandChild) {
        GrandChild({ message: new Message('grandchild') })
          .reuseId('GrandChild')
      }
    }
  }
}

@Reusable
@Component
struct GrandChild {
  @State message: Message = new Message('GrandChild');
  @State label: string = 'HelloWorld';
  @ComponentInit
  myInit() {
    hilog.info(0x0000, 'testTag', 'GrandChild myInit');
  }
  @ComponentAppear
  myAppear() {
    this.label = 'myAppear';
    hilog.info(0x0000, 'testTag', 'GrandChild myAppear');
  }
  @ComponentBuilt
  myBuilt() {
    this.label = 'myBuilt';
    hilog.info(0x0000, 'testTag', 'GrandChild myBuilt');
  }
  @ComponentRecycle
  myRecycle() {
    this.label = 'myRecycle';
    hilog.info(0x0000, 'testTag', 'GrandChild myRecycle');
  }
  @ComponentDisappear
  myDisappear() {
    this.label = 'myDisappear';
    hilog.info(0x0000, 'testTag', 'GrandChild myDisappear');
  }
  @ComponentReuse
  myReuse(params?: Record<string, Object | undefined | null>) {
    this.label = 'myReuse';
    hilog.info(0x0000, 'testTag', 'GrandChild myReuse');
  }

  build() {
    Column() {
      Text(this.message.value)
        .fontSize(30)
        .margin(10)
    }
  }
}

以上示例中,Index页面包含自定义组件Child,Child组件包含自定义组件GrandChild。Child和GrandChild分别声明了各自的自定义组件生命周期装饰器装饰的函数(myInit / myAppear / myBuilt / myRecycle / myReuse / myDisappear)。

Child myInit
Child myAppear
GrandChild myInit
Child myBuilt
GrandChild myAppear
GrandChild myBuilt
Child myRecycle
GrandChild myRecycle

[h2]自定义组件生命周期的注册监听

CustomComponentLifecycleObserver用于监听自定义组件的生命周期,开发者可以根据自己的需求重写CustomComponentLifecycleObserver中的回调函数。

import { ComponentInit, ComponentDisappear, UIUtils, CustomComponentLifecycleObserver, CustomComponentLifecycle } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

export class Message {
  public value: string | undefined;
  constructor(value: string) {
    this.value = value;
  }
}

@Entry
@Component
struct Index {
  @State changeChild: boolean = true;

  build() {
    Column() {
      Button(this.changeChild ? 'recycle child' : 'reuse child')
        .margin(10)
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {
          this.changeChild = !this.changeChild;
        })
      if (this.changeChild) {
        // 如果只有一个复用的组件,可以不用设置reuseId。
        Child({ message: new Message('child') })
          .reuseId('Child')
      }
    }
    .width('100%')
  }
}

@Reusable
@Component
struct Child {
  @State message: Message = new Message('AboutToReuse');
  @ComponentInit
  myInit(): void {
    registerObserver(UIUtils.getLifecycle(this));
  }
  @ComponentDisappear
  myDisappear(): void {
    unRegisterObserver(UIUtils.getLifecycle(this));
  }

  build() {
    Column() {
      Text(this.message.value)
        .fontSize(30)
    }
  }
}

export class MyObserver implements CustomComponentLifecycleObserver {
  // 重写CustomComponentLifecycleObserver中的生命周期事件,CustomComponentLifecycleObserver无法监听父组件的aboutToInit
  aboutToAppear() {
    hilog.info(0x0000, 'testTag', 'MyObserver aboutToAppear');
  }
  onDidBuild() {
    hilog.info(0x0000, 'testTag', 'MyObserver onDidBuild');
  }
  aboutToReuse(params?: Record<string, Object | undefined | null>) {
    // params存在时,为V1的复用;
    hilog.info(0x0000, 'testTag', 'MyObserver aboutToReuse');
  }
  aboutToRecycle() {
    hilog.info(0x0000, 'testTag', 'MyObserver aboutToRecycle');
  }
  // 在父组件的aboutToDelete函数中解除注册监听,则无法监听父组件的aboutToDisappear
  aboutToDisappear() {
    hilog.info(0x0000, 'testTag', 'MyObserver aboutToDisappear');
  }
}

// 创建Observer对象
const observer = new MyObserver();
export function registerObserver(lifeCycle: CustomComponentLifecycle) {
  // 向lifeCycle注册监听
  lifeCycle.addObserver(observer);
}
export function unRegisterObserver(lifeCycle: CustomComponentLifecycle) {
  // 向lifeCycle取消注册监听
  lifeCycle.removeObserver(observer);
}

在@ComponentDisappear装饰的函数中解除注册监听,所以监听器无法监听到aboutToDisappear。

按两次按钮,然后关闭程序,此时日志输出信息如下:

MyObserver aboutToAppear
MyObserver onDidBuild
MyObserver aboutToRecycle
MyObserver aboutToReuse

不建议在组件的onAppear和onDisAppear中注册和解除监听。在onAppear中注册监听,此时组件已经处于BUILT状态,所以无法监听组件的aboutToAppear和onDidBuild。

Column() {
  Text('Hello World')
}
.onAppear(() => {
  // 在onAppear中注册监听
  registerObserver(UIUtils.getLifecycle(this));
})
.onDisAppear(() => {
  unRegisterObserver(UIUtils.getLifecycle(this));
})

生命周期回调函数的区别

[h2]@ComponentAppear、@ComponentDisappear与aboutToAppear、aboutToDisappear的区别

自定义组件在INIT状态时,即将转化为APPEARED时,先调用aboutToAppear后调用@ComponentAppear装饰的函数。

自定义组件在INIT状态、BUILT状态或RECYCLED状态时,即将转化为DISAPPEARED时,先调用@ComponentDisappear装饰的函数后调用aboutToDisappear。

aboutToAppear是自定义组件build之前执行,aboutToDisappear是自定义组件销毁前执行。但有时自定义组件没有build,就被销毁。为了执行一个完整的生命周期,aboutToDisappear会判断,该组件是否执行了aboutToAppear,如果没有执行便强制触发一次aboutToAppear。@ComponentAppear装饰的函数和@ComponentDisappear装饰的函数受状态机约束,@ComponentDisappear装饰的函数不会误调用@ComponentAppear装饰的函数。例子如下所示:

// Index.ets
import { SwiperExample } from './SwiperPage';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State show: boolean = false;

  build() {
    RelativeContainer() {
      Text('start')
        .fontSize(50)
        .fontColor('#000')
        .id('text')
        .alignRules({
          top: { anchor: '__container__', align: VerticalAlign.Top },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          // this.show为true,创建SwiperExample;this.show为false,销毁SwiperExample
          this.show = !this.show;
        })
      if (this.show) {
        SwiperExample()
          .id('TableExample')
          .alignRules({
            bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
            middle: { anchor: '__container__', align: HorizontalAlign.Center }
          })
          .width('100%')
          .height('auto')
      }
    }
    .height('100%')
    .width('100%')
  }
}
import { ComponentAppear, ComponentDisappear } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Component
export struct SwiperPage {
  @State name: number = 0;
  aboutToAppear(): void {
    hilog.info(0x0000, 'testTag', 'SwiperPage aboutToAppear %{public}d', this.name);
  }
  aboutToDisappear(): void {
    hilog.info(0x0000, 'testTag', 'SwiperPage aboutToDisappear %{public}d', this.name);
  }
  @ComponentAppear
  myAppear(): void {
    hilog.info(0x0000, 'testTag', 'SwiperPage myAppear %{public}d', this.name);
  }
  @ComponentDisappear
  myDisappear(): void {
    hilog.info(0x0000, 'testTag', 'SwiperPage myDisappear %{public}d', this.name);
  }

  build() {
    Text(this.name.toString())
      .width('90%')
      .height(160)
      .fontColor(Color.Black)
      .backgroundColor(0xAFEEEE)
      .textAlign(TextAlign.Center)
      .fontSize(30)
  }
}

class MyDataSource implements IDataSource {
  public list: number[] = [];
  constructor(list: number[]) {
    this.list = list;
  }
  totalCount(): number {
    return this.list.length;
  }
  getData(index: number): number {
    return this.list[index];
  }
  registerDataChangeListener(listener: DataChangeListener): void {}
  unregisterDataChangeListener() {}
}

@Entry
@Component
export struct SwiperExample {
  private swiperController: SwiperController = new SwiperController()
  private data: MyDataSource = new MyDataSource([])
  @State selectedTabIndex: number = 0;
  @ComponentAppear
  myAppear(): void {
    // myAppear中为data赋值
    let list: number[] = [];
    for (let i = 0; i <= 11; i++) {
      list.push(i);
    }
    this.data = new MyDataSource(list);
  }

  build() {
    Column({ space: 5 }) {
      Swiper(this.swiperController) {
        ForEach(this.data.list, (item: number) => {
          SwiperPage({
            name: item
          })
        })
      }
      .index(this.selectedTabIndex)
      .autoPlay(false)
      .disableSwipe(true)
      .indicator(false)
      .width('100%')
      .cachedCount(2) // 以当前节点为基础,往前缓存两个节点,往后缓存两个节点
      .onChange((index) => {
        this.selectedTabIndex = index;
      })
      Row({ space: 12 }) {
        Button('showNext')
          .onClick(() => {
            this.swiperController.showNext();
          })
        Button('showPrevious')
          .onClick(() => {
            this.swiperController.showPrevious();
          })
      }
      .margin(5)
    }
    .width('100%')
    .margin({ top: 5 })
  }
}

启动程序后,先按start按钮,此时只有Swiper缓存的五个节点开始执行aboutToAppear和myAppear,非缓存的节点未触发aboutToAppear和myAppear。

日志输出信息如下:

SwiperPage aboutToAppear 0
SwiperPage myAppear 0
SwiperPage aboutToAppear 11
SwiperPage myAppear 11
SwiperPage aboutToAppear 1
SwiperPage myAppear 1
SwiperPage aboutToAppear 10
SwiperPage myAppear 10
SwiperPage aboutToAppear 2
SwiperPage myAppear 2

此时关闭程序,缓存的五个节点正常触发aboutToDisappear,但是非缓存的节点触发aboutToDisappear前,会强制触发aboutToAppear。无论是否是缓存节点,myDisappear不会误触发myAppear。

SwiperPage myDisappear 0
SwiperPage aboutToDisappear 0
SwiperPage myDisappear 1
SwiperPage aboutToDisappear 1
SwiperPage myDisappear 2
SwiperPage aboutToDisappear 2
SwiperPage aboutToAppear 3
SwiperPage myDisappear 3
SwiperPage aboutToDisappear 3
SwiperPage aboutToAppear 4
SwiperPage myDisappear 4
SwiperPage aboutToDisappear 4
...

[h2]@ComponentReuse、@ComponentRecycle与aboutToReuse、aboutToRecycle的区别

自定义组件在RECYCLED状态时,即将转化为BUILT时,先调用aboutToReuse后调用@ComponentReuse装饰的函数。

自定义组件在BUILT状态时,即将转化为RECYCLED时,先调用aboutToRecycle后调用@ComponentRecycle装饰的函数。

import { ComponentAppear, ComponentBuilt, ComponentReuse } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

@Entry
@Component
struct ReusableTest {
  @State flag1: boolean = true;
  @State flag2: boolean = false;
  build() {
    Column() {
      // 点击Button切换flag1,触发ReusableComp1和ReusableComp2的回收/复用
      Button('change flag 1')
        .margin(10)
        .onClick(() => {
          this.flag1 = !this.flag1;
        })
      // 点击Button切换flag2,触发ReusableComp1和ReusableComp3的回收/复用
      Button('change flag 2')
        .margin(10)
        .onClick(() => {
          this.flag2 = !this.flag2;
        })
      if (this.flag1) {
        ReusableComp1({ flag: true })
      }
      if (this.flag2) {
        ReusableComp1({ flag: false })
      }
    }
    .width('100%')
  }
}

@Reusable
@Component
struct ReusableComp1 {
  @Require @Prop flag: boolean = true;
  build() {
    if (this.flag) {
      ReusableComp2()
    } else {
      ReusableComp3()
    }
  }
}

@Reusable
@Component
struct ReusableComp2 {
  build() {
    Text('ReusableComp2')
      .margin(10)
  }
}

@Reusable
@Component
struct ReusableComp3 {
  aboutToAppear(): void {
    hilog.info(0x0000, 'testTag', 'ReusableComp3 aboutToAppear');
  }
  aboutToReuse(params: Record<string, Object | undefined | null>): void {
    hilog.info(0x0000, 'testTag', 'ReusableComp3 aboutToReuse');
  }
  @ComponentReuse
  myReuse(params: Record<string, Object | undefined | null>): void {
    hilog.info(0x0000, 'testTag', 'ReusableComp3 myReuse');
  }
  @ComponentAppear
  myAppear(): void {
    hilog.info(0x0000, 'testTag', 'ReusableComp3 myAppear');
  }
  @ComponentBuilt
  myBuilt(): void {
    hilog.info(0x0000, 'testTag', 'ReusableComp3 myBuilt');
  }

  build() {
    Text('ReusableComp3')
      .margin(10)
  }
}

按下change flag 1按钮,此时ReusableComp2进入回收状态,再按下change flag 2按钮,此时ReusableComp3第一次被创建,此时日志输出信息如下:

ReusableComp3 aboutToReuse
ReusableComp3 aboutToAppear
ReusableComp3 myAppear
ReusableComp3 myBuilt

ReusableComp3从未创建过,但按下change flag 2按钮后,ReusableComp3的aboutToReuse误调用,同时ReusableComp3的aboutToAppear和myBuilt被调用。而myReuse没有被误调用,这是因为myReuse受状态机约束,当组件不是RECYCLED状态时,不会执行myReuse。