DEV Community

HarmonyOS
HarmonyOS

Posted on

Repeated Page Rendering Occurs When TabContent Is Switched Between Tabs

Read the original article:Repeated Page Rendering Occurs When TabContent Is Switched Between Tabs

Problem Description

When switching between TabContents in the Tabs, there is an issue of duplicate rendering of the page. Each time a subpage is switched, the position of the text changes. The problematic code is as follows:

@Entry
@Component
struct Index {
  @State index: number = 0;
  @State arr: Array<string> = ['a', 'b', 'c']

  build() {
    Tabs() {
      ForEach(this.arr, (item: string) => {
        TabContent() {
          Column() {
            Text('Page' + item)
          }
          .justifyContent(this.index === 1 ? FlexAlign.End : FlexAlign.Start)
          .alignItems(HorizontalAlign.Center)
          .width('100%')
          .height('100%')
        }
      }, (item: string) => item)
    }.onChange((index: number) => {
      this.index = index
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

Background Knowledge

  • Tabs: A container component that allows switching between content views via tabs, with each tab corresponding to one content view.
  • Child Components: Custom components are not supported as child components. Only the child component TabContent, as well as rendering control types if/else and ForEach, are allowed. Under if/else and ForEach, only TabContent is supported; custom components are not supported.

Troubleshooting Process

The content of the tab subpages is rendered when they are first displayed upon switching. Subsequent switches back to these subpages do not trigger a redraw automatically.
In the code mentioned above, this.index === 1 is used to control the layout of the subpages. However, since index is a state variable decorated with @State, its value changes every time the tab is switched, which causes the subpages to refresh and results in duplicate page rendering issues.

Analysis Conclusion

Using state variables to control the layout of subpages, and changing the value of the state variable every time a switch occurs, leads to frequent redrawing of the subpages.

Solution

When rendering TabContent, avoid using a constantly changing index value; instead, use the index from ForEach for comparison.

@Entry
@Component
struct Index {
  @State index: number = 0;
  @State arr: Array<string> = ['a', 'b', 'c']

  build() {
    Tabs() {
      ForEach(this.arr, (item: string, aIndex: number) => {
        TabContent() {
          Column() {
            Text('Page' + item)
          }
          .justifyContent(aIndex === 1 ? FlexAlign.End : FlexAlign.Start)
          .alignItems(HorizontalAlign.Center)
          .width('100%')
          .height('100%')
        }
      }, (item: string) => item)
    }.onChange((index: number) => {
      this.index = index
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

Written by Mehmet Emir Ucar

Top comments (0)