簡體   English   中英

Meteor userId存在但用戶未定義

[英]Meteor userId is present but user is undefined

渲染我的反應組件時,我得到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密鑰。 由於您已關閉自動發布,因此您可能希望從用戶發布您自己的特定密鑰集。

我通常有:

服務器:

Meteor.publish('me',function(){
  if ( this.userId ) return Meteor.users.find(this.userId,{ fields: { key1: 1, key2: 1 ...}});
  this.ready();
});

客戶:

Meteor.subscribe('me');

您還可以發布有關其他用戶的信息,但是要共享的密鑰列表通常要小得多。 例如,您通常不希望與登錄用戶共享其他用戶的電子郵件地址。

Meteor.user()確實無法直接使用,您可以嘗試以下方法:

Tracker.autorun(function(){
  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,然后打印正確的用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM