Read the original article:How to resolve the issue of onPageShow callback not working?
Requirement Description
When entering a page, the onPageShow callback inside a custom component does not take effect. The goal is to ensure the expected lifecycle behavior when displaying custom components in HarmonyOS.
Background Knowledge
- The
onPageShowcallback is triggered each time a router page is displayed and only works in components decorated with@Entry. This includes scenarios such as route navigation and app foreground activation. - The
aboutToAppearlifecycle method is executed after the creation of a new component instance but before itsbuild()function runs. It allows modifying state variables before rendering. - If a component with
onPageShowis used as a child component, the callback will not be triggered because only top-level (entry) components support it.
Implementation Steps
- Identify the root cause: the
onPageShowcallback is not triggered because the component is used as a child component. - Replace
onPageShowwithaboutToAppearto ensure code executes before rendering. - Keep only one
@Entrydecorator in the app (typically at the root page). - Use the parent component to handle navigation lifecycle events and pass data to child components using
@Provide/@Consume.
Code Snippet / Configuration
Incorrect Implementation (Issue Example):
@Component
export struct SplashPage {
onPageShow() {
console.info(`onPageShow`);
}
build() {
Text('SplashPage')
.fontSize(50)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%');
}
}
Fixed Implementation:
@Component
export struct SplashPage {
aboutToAppear(): void {
console.info(`aboutToAppear`);
}
build() {
Text('SplashPage')
.fontSize(50)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%');
}
}
Index Page:
import { SplashPage } from './SplashPage';
@Entry
@Component
struct Index {
build() {
Column() {
SplashPage();
};
}
}
Test Results
- The
onPageShowcallback was not triggered when used as a child component. - After replacing it with
aboutToAppear, logs confirmed that the callback executed correctly before component rendering.
Limitations or Considerations
- Only components decorated with
@Entrycan useonPageShow. Child components should useaboutToAppear.
Related Documents or Links
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/arkts-create-custom-components#entry
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/arkts-provide-and-consume
Top comments (0)