繁体   English   中英

Meteor重新启动时Meteor.users尚未准备好

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM