无法读取 meteor 函数中未定义的属性'profile'.JS?



我有以下代码:

Template.analyze.userFullName = function() {
    var u = Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}});
    return u.profile.name;
};

Meteor.users.findOne({_id: this.userId}, {fields: {name: 1}})在控制台中使用时返回以下内容:

Object
    _id: "79ef0e67-6611-4747-b669-45cc163cc1d8"
    profile: Object
        name: "My Name"

但是当我在上面的代码中使用它时,我得到了这个:Uncaught TypeError: Cannot read property 'profile' of undefined

为什么会发生这种情况?我要做的就是检索用户配置文件中的全名,并将其传递给模板部分。

当用户尚未可用时,模板在页面加载时立即呈现,这会导致错误。幸运的是,因为你使用的是用户集合,它是响应式的,你可以让它在可用时重新渲染。首先要检查对象是否为空:

Template.analyze.userFullName = function() {
    // use Meteor.user() since it's available
    if (Meteor.user())
      return Meteor.user().profile.name;
};

这样,当user为null时(在加载期间),模板就不会抛出错误。当数据可用时,响应性将立即再次调用模板,并在屏幕上呈现。

最新更新