2016-06-28 47 views
0

我正在尝试使用Meteor显示登录用户的电子邮件地址。Meteor - 显示登录用户的电子邮件地址

我正在使用命令Meteor.user()。emails [0] .address - 并且这个工作有时只是。其他时候它是未定义的。这是因为有时在用户集合可用之前页面呈现。

但是,我正在使用React而不是开火。每个在线解决方案都建议在模板的onCreated部分使用Meteor.subscribe()。但我找不出React的等价物,我无法弄清楚如何在渲染之前等待User集合。

回答

0

已更新为使用Meteor.autorun,它接受每当Meteor的被动源更新时运行的回调函数。

Meteor.subscribe接受onReady可选回调。我会附加到您的React组件上的componentWillMount生命周期事件,设置您的流星订阅,并且一旦onReady发起了一次状态更改。这里是一些粗略的示例代码;

var Foo = React.createClass({ 
    componentWillMount: function() { 
    var _this = this; 

    // Setup meteor subscription 
    Meteor.autorun(function() { 
     _this.setState({ 
     user: Meteor.user(), 
     }); 
    }) 
    }, 
    render: function() { 
    // Render nothing until we have a user 
    if (!this.state || !this.state.user) { 
     return null; 
    } 

    // Render the address when we have the user 

    return (
     <div>{this.state.user.emails[0].address}</div> 
    ); 
    } 
}); 

相关的文档:http://docs.meteor.com/api/pubsub.html#Meteor-subscribe

+0

我尝试这样的代码,但它不会显示。我的发布命令应该是什么样子? – Laugh7

+0

更新为使用Meteor.autorun。我对Meteor代码并不是非常熟悉,所以我不能肯定地说你为什么不能订阅Users集合。自动运行会在被动源发生变化时执行其回调,因此对于这种情况非常有效。这里是一篇博客文章,讨论自动运行https://www.discovermeteor.com/blog/reactivity-basics-meteors-magic-demystified/ –

相关问题