Ionic pages not cached

2019-08-23 10:15发布

I got two pages:

  • HomePage
  • AboutPage

HomePage is the rootPage.

At startup HomePage#ionViewDidLoad is called. I navigate from the HomePage to the AboutPage using the NavController:

navigateToAbout(): void {
   this.navCtrl.push('AboutPage');
}

Everytime I navigate to the AboutPage, AboutPage#ionViewDidLoad is called. If I navigate back to the HomePage with ion-navbar, HomePage#ionViewDidLoad is not called but if I use navCtrl.push('HomePage'), HomePage#ionViewDidLoad is called again.

Can someone explain, why ionViewDidLoad is called everytime if I use navCtrl.push(...). According to the Ionic NavController Doc the Pages should be cached and ionViewDidLoad should be called only once per Page:

View creation

By default, pages are cached and left in the DOM if they are navigated away from but still in the navigation stack (the exiting page on a push() for example). They are destroyed when removed from the navigation stack (on pop() or setRoot()).

ionViewDidLoad

Runs when the page has loaded. This event only happens once per page being created. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The ionViewDidLoad event is good place to put your setup code for the page.

1条回答
仙女界的扛把子
2楼-- · 2019-08-23 10:26

Because if you use the navbar to navigate back to the HomePage the pop() method is used. If you use push('HomePage') on the AboutPage you create a new instance of the HomePage and subsequently ionViewDidLoad() is invoked.

Only pages that are already on the navigation stack are cached (like the HomePage when you push the AboutPage the first time) but pages that are pushed to the nav stack are always newly created.

Maybe this example helps to visualize this:

1. Initial state after startup:

[HomePage]

2. State after nav.push('AboutPage'):

[HomePage, AboutPage]
 ^^^^^^^^
  cached

3. State if you use the navbar to navigate back or pop():

[HomePage] // The cached instance is used so ionViewDidLoad() is not called

4. State if you use .push('HomePage') after the second step:

[HomePage, AboutPage, HomePage] // a new instance is created so ionViewDidLoad() is called
 ^^^^^^^^  ^^^^^^^^^
  cached    cached
查看更多
登录 后发表回答