简体   繁体   中英

Displaying Meteor.user()

I have this template:

<template name="index">
  {{#if currentUser}
    {{userid}}
  {{/if}}
</template>

What is the difference between

Template.index.helpers({
    userid: function() {
        return Meteor.user()._id;
    }
});

AND

Template.index.helpers({
    userid: Meteor.user()._id
});

The last one gives this error: Uncaught TypeError: Cannot read property '_id' of undefined

The easiest thing to do is use {{currentUser._id}}

Meteor.user()._id is correct. The problem is when you load the page, initially the data is not available and Meteor.user() will be null until a DDP connection is established and your browser logs you in (this takes a few hundred milliseconds). Meteor.user() && Meteor.user()._id to correct this.

The difference between the two Meteor.user()._id is in one you are passing the first static value that loads when the template is loaded. It will stick to being that even if Meteor.user() changes, or you log out.

When you pass a function you tell the helper it can be recalculated and it will update if there are any reactive changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM