Ionic pages not cached

旧城冷巷雨未停 提交于 2019-12-11 16:27:47

问题


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:


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


来源:https://stackoverflow.com/questions/46970463/ionic-pages-not-cached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!