已更新为使用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
我尝试这样的代码,但它不会显示。我的发布命令应该是什么样子? – Laugh7
更新为使用Meteor.autorun。我对Meteor代码并不是非常熟悉,所以我不能肯定地说你为什么不能订阅Users集合。自动运行会在被动源发生变化时执行其回调,因此对于这种情况非常有效。这里是一篇博客文章,讨论自动运行https://www.discovermeteor.com/blog/reactivity-basics-meteors-magic-demystified/ –