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...
但是constructor
和ionViewDidLoad
之间的主要区别在于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
.每次进入页面时,都会触发ionViewWillEnter
或ionViewDidEnter
.
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.