HarmonyOS鸿蒙Next中Tabs组件内ForEach包含TabContent导致aboutToAppear函数执行多次

HarmonyOS鸿蒙Next中Tabs组件内ForEach包含TabContent导致aboutToAppear函数执行多次

@ComponentV2 struct A { aboutToAppear(): void { console.log(‘test:A’) }

build() { Column() { Text(‘首页’).fontSize(30) } } }

@ComponentV2 struct B { aboutToAppear(): void { console.log(‘test:B’) }

build() { Column() { Text(‘第二页’).fontSize(30) } } }

@Entry @Component struct IndexPage { @State currentIndex: number = 0 @State data: Array<number> = [0, 1]

@Builder tabBarBuild(tabInfo: number) { Column() { Text(‘页面’ + tabInfo) .fontSize(14) .fontColor(this.currentIndex === tabInfo ? Color.Red : Color.Black) } }

build() { Column() { Tabs({ index: this.currentIndex, barPosition: BarPosition.End }) { ForEach(this.data, (tabInfo: number) => { TabContent() { if (this.currentIndex === this.data[0]) { A() } else if (this.currentIndex === this.data[1]) { B() } } .tabBar(this.tabBarBuild(tabInfo)) }) } .onTabBarClick((index: number) => { this.currentIndex = index }) .scrollable(false) .barMode(BarMode.Fixed) } } }

最小代码如上,使用ForEach会导致切换tab的时候重复输出test:A和test:B,期望输出仅有一次。


更多关于HarmonyOS鸿蒙Next中Tabs组件内ForEach包含TabContent导致aboutToAppear函数执行多次的实战教程也可以访问 https://www.itying.com/category-93-b0.html

6 回复

@ComponentV2 struct A { aboutToAppear(): void { console.log(‘test:A’) }

build() { Column() { Text(‘首页’).fontSize(30) } } }

@ComponentV2 struct B { aboutToAppear(): void { console.log(‘test:B’) }

build() { Column() { Text(‘第二页’).fontSize(30) } } }

@Entry @Component struct Index { @State currentIndex: number = 0 @State data: Array<number> = [0, 1]

@Builder tabBarBuild(tabInfo: number) { Column() { Text(‘页面’ + tabInfo) .fontSize(14) .fontColor(this.currentIndex === tabInfo ? Color.Red : Color.Black) } }

build() { Column() { Tabs({ index: this.currentIndex, barPosition: BarPosition.End }) { ForEach(this.data, (tabInfo: number) => { TabContent() { this.customPage(this.currentIndex) } .tabBar(this.tabBarBuild(tabInfo)) }) }.onTabBarClick((index: number) => { this.currentIndex = index }) .scrollable(false) .barMode(BarMode.Fixed) } }

@Builder customPage(index: number) { if (index === this.data[0]) { A() } else if (index === this.data[1]) { B() } } }

更多关于HarmonyOS鸿蒙Next中Tabs组件内ForEach包含TabContent导致aboutToAppear函数执行多次的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


这样确实可以解决,想请问下原理是什么呢?

有要学HarmonyOS AI的同学吗,联系我:https://www.itying.com/goods-1206.html

声明式UI框架会在状态变化时重新构建整个组件树。将页面内容的逻辑从 ForEach 中抽离出来,避免直接在 ForEach 内部动态创建组件。这样 ForEach 只负责生成 TabContent,而具体的页面内容由 customPage 方法决定。customPage 的逻辑是基于 index 的静态判断,框架能够识别出哪些组件需要更新,哪些可以复用,避免不必要的重新初始化。

this.customPage(this.currentIndex)这个实际上写为this.customPage(tabInfo)更合适一些,

在HarmonyOS鸿蒙Next中,Tabs组件内使用ForEach包含TabContent时,aboutToAppear函数可能会多次执行。这是因为ForEach在每次渲染时都会重新创建子组件,导致TabContent的aboutToAppear被多次触发。建议优化ForEach的使用,避免不必要的组件重建,或通过条件判断控制aboutToAppear的执行逻辑。

回到顶部