[英]Meteor.users is not ready when Meteor restarts
開發時,每次保存文件時,Meteor都會重新啟動(這是一項出色的功能),但是某些頁面會根據用戶個人資料進行一些驗證,並將它們重定向到登錄頁面。 我正在檢查,看來Meteor.users尚未准備好。 如何分類?
SpecialController = MainController.extend({
onBeforeAction: function(){
const user = Meteor.users.findOne({_id: Meteor.userId()});
if (user && user.profile.internalStatus == "valid") {
this.next();
} else {
// the routers is sending here but it shouldn't.
Router.go('dashboard');
}
}
});
您不會立即獲得Mereor.userId()
,因為其准備工作會Mereor.userId()
延遲。
您可以使用Tracker.autorun
跟蹤Meteor.userId()
的准備情況。 Tracker.autorun
允許函數在依賴的反應性數據源發生更改時自動被調用。
簡而言之, Tracker.autorun()
將一個函數作為輸入,運行此函數並在以后數據源發生更改時返回。
對於您的情況,可以使用Tracker.autorun()
來跟蹤userId
,因為Meteor.user()
和Meteor.userId()
是反應性的。 在componentDidMount()
調用Tracker.autorun()
並將userId
更改時保存在其他位置。
希望以下代碼段對您有所幫助:
componentDidMount() {
var context = this;
Tracker.autorun(function() {
let userId = Meteor.userId();
if (userId != undefined) {
context.setState({ userId: userId });
}
});
}
使用Rahman的答案,您可以像這樣在componentDidMount
編寫代碼:
componentDidMount() {
Tracker.autorun(() => {
let userId = Meteor.userId();
if (userId != undefined) {
this.setState({ userId: userId });
}
});
}
Arrow函數將其容器上下文用作this
。
您可以創建一個接受回調並僅在客戶端准備好所有需要的數據后才執行的函數。
Meteor.runWithFullUser = function(cb) {
Tracker.autorun((c) => {
const user = Meteor.user();
if(typeof user.profile !== 'undefined') {
cb();
c.stop();
}
});
}
然后用這個
SpecialController = MainController.extend({
onBeforeAction: function(){
Meteor.runWithFullUser(() => {
const user = Meteor.users.findOne({_id: Meteor.userId()});
if (user && user.profile.internalStatus == "valid") {
this.next();
} else {
// the routers is sending here but it shouldn't.
Router.go('dashboard');
}
});
}
});
為了確保您在運行此方法時具有Meteor.userId()
。 您必須確保僅在存在Meteor.userId()
時才呈現模板。 為此,您可以使用頂層布局模板並執行類似的操作
<template name="layout">
...
{{#if currentUser}}
...
{{else}}
{{> appLayout}}
{{/if}}
</template>
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.