流星重新启动时,我们的用户还没有准备好



在开发时,每次我保存文件流星重新启动(这是一个出色的功能),但是一些页面具有基于用户配置文件的一些录音,并且它们会重定向到着陆页。我正在检查,似乎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');
    }
  }
});

使用Rahman的答案,您可以简单地在componentDidMount中写下代码:

componentDidMount() {
   Tracker.autorun(() => {
      let userId = Meteor.userId();
      if (userId != undefined) {
         this.setState({ userId: userId });
      }
   });
}

箭头函数使用其容器上下文作为this

您不会立即获得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 });
            }
        });
    }

您可以创建一个函数,该函数只有在客户端准备所有需要的数据时才进行回调。

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>

希望这会有所帮助。

相关内容

最新更新