开发时,每次我保存文件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');
}
}
});
答案 0 :(得分:2)
你不会马上得到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 });
}
});
}
答案 1 :(得分:1)
使用Rahman的答案,你可以简单地在pip install minisom
中编写代码:
componentDidMount
箭头函数将其容器上下文用作componentDidMount() {
Tracker.autorun(() => {
let userId = Meteor.userId();
if (userId != undefined) {
this.setState({ userId: userId });
}
});
}
。
答案 2 :(得分:1)
您可以创建一个函数,该函数仅在客户端准备好所有需要的数据时才进行回调并执行它。
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>
希望这会有所帮助。