在渲染我的 React 组件时,我得到了 Meteor.user()
null
。然后我尝试访问 Meteor.userId()
并将其正确设置为登录用户的 ID。还尝试通过 Meteor.users.findOne()
访问用户,但没有成功。
我的问题是,为什么用户对象是未定义的,尽管用户 ID 是可访问的?
我使用以下代码片段进行测试:
var uid = Meteor.userId();
console.log(uid); // printed the _id correctly
var usr = Meteor.user();
console.log(usr); // undefined
var usr1 = Meteor.users.findOne({_id: uid});
console.log(usr1); // undefined
最佳答案
Meteor.userId()
在登录后立即可用。 Meteor.user()
要求通过 DDP 将对象交付给客户端,因此它不会立即可用。
默认情况下,profile
key 已发布。由于您关闭了自动发布,您可能希望从用户那里发布您自己的一组特定 key 。
我通常有:
服务器:
Meteor.publish('me',function(){
if ( this.userId ) return Meteor.users.find(this.userId,{ fields: { key1: 1, key2: 1 ...}});
this.ready();
});
客户:
Meteor.subscribe('me');
您还可以发布有关其他用户的信息,但要共享的 key 列表通常要小得多。例如,您通常不想与登录用户共享其他用户的电子邮件地址。
关于javascript - Meteor userId 存在但用户未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40468191/