ionViewDidLoad()函数的作用是什么? [英] What is the purpose of the ionViewDidLoad() function?

查看:753
本文介绍了ionViewDidLoad()函数的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行ionic g page pageName时,我生成了.ts,.css和.html文件.

On running ionic g page pageName I get generated .ts,.css and .html files.

在.ts文件中,我有一个名为ionViewDidLoad(){}的函数,该函数在视图显示之前就已打印出来.

Inside the .ts file I have a function called ionViewDidLoad(){} and this is getting printed before my view appears.

我相信这可以在构造函数本身中完成吗?

This can be done in constructor itself I believe?

有人可以给我一些有关此功能的博客参考或解释吗?

Can someone give me some reference of any blog or explanation about this function?

推荐答案

是的,很多事情都可以在构造函数或ionViewDidLoad中完成,结果将是相同的...

You're right, a lot of things could be done both in the constructor or in the ionViewDidLoad and the result will be the same...

但是constructorionViewDidLoad 之间的主要区别在于constructor仅执行一次(在实例化组件时),而ionViewDidLoad方法将被执行每次进入(加载)视图.

But the main difference between the constructor and the ionViewDidLoad is that the constructor will be executed only once (when the component gets instantiated) but the ionViewDidLoad method will be executed every time the view is entered (loaded).

例如,如果要从远程数据源加载数据,则在构造函数中进行加载时,数据将仅获得一次.如果这些数据可以足够快地更改,那么一种更好的方法是使用ionViewDidLoad方法获取它,以确保每次加载该页面时,都会获取最新数据并显示在视图中.

For instance, if you want to load data from a remote datasource, if you do it in the constructor, the data will be obtained only once. If that data could change fast enough, a better approach would be to obtain it in the ionViewDidLoad method, to be sure that every time the page is loaded, the latest data is being obtained and shown in the view.

关于ionViewDidLoad 的另一个重要事实是,有时您想与DOM交互(可能是初始化地图).

Another important fact about the ionViewDidLoad is that sometimes you want to interact with the DOM (maybe to initialize a map).

在这种情况下,如果尝试在构造函数中访问DOM,则将注意到DOM尚未准备就绪,因此您将无法获取map元素.正确的方法是在ionViewDidLoad内部,因为到那时(正如名称所说),视图已经加载,并且DOM现在可用.

In that case, if you try to access the DOM in the constructor, you will notice that the DOM is not ready by that point and you won't be able to get the map element. The correct approach to do it would be inside the ionViewDidLoad because at that point (just like the name says) the view was already loaded and the DOM is now available.

更新:

就像下面的注释中指出的@graphefruit一样,在最新版本的Ionic 2中,如果未缓存页面,则只会触发 ionViewDidLoad.每次进入页面时,都会触发ionViewWillEnterionViewDidEnter.

Just like @graphefruit pointed out in the comment below, in the newest versions of Ionic 2, ionViewDidLoad just fires if the page is not cached. ionViewWillEnter or ionViewDidEnter will be fired every time the page is entered.

这篇关于ionViewDidLoad()函数的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆