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

查看:42
本文介绍了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 尚未准备好,您将无法获取地图元素.正确的做法应该是在 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天全站免登陆