【问题标题】:Waiting on Meteor.user()等待 Meteor.user()
【发布时间】:2016-12-07 11:57:46
【问题描述】:

如果有新用户注册,我会将他们带到入门路线,这样他们就可以输入/gs 的名称。我将名称存储在当前用户的配置文件对象的名称属性中。现在,如果用户已经输入了名称并访问了/gs 路由,我想将他们重定向到根目录。在铁路由器中,我这样做:

Router.route('/gs', {
  name: 'gs',
  onBeforeAction: function() {
    if ( Meteor.user().profile.name ) {
      this.redirect('/');
    } else {
      this.render();
    }
  }
});

即使这样有效,它也会向控制台打印 2 个错误。其中之一是“无法读取未定义的属性'配置文件'”和缺少this.next()。任何解决这些问题的方法。

【问题讨论】:

  • 试试这个:if ( Meteor.user() && Meteor.user().profile.name ) {

标签: javascript meteor iron-router


【解决方案1】:

您的路由函数和大多数钩子都是在反应式计算中运行的。这意味着如果响应式数据源发生更改,它们将自动重新运行。例如,如果您在路由函数内部调用 Meteor.user(),则每次 Meteor.user() 的值更改时,您的路由函数都会重新运行。 (Iron.Router Guide: Reactivity)

钩子函数和在调度到路由时运行的所有函数都在反应式计算中运行:如果任何反应式数据源使计算无效,它们将重新运行。在上面的例子中,如果 Meteor.user() 改变了整个路由函数集将再次运行。 (Iron.Router Guide: Using Hooks)

函数第一次运行时,Meteor.user()undefined。然后它的值变为一个对象。因为它是一个反应变量,所以再次运行该函数,这次没有错误。

您应该在使用其属性之前检查是否定义了Meteor.user()。这是一个非常(可能太多)详尽的方法:

if (Meteor.user() !== undefined) {
  // the user is ready
  if (Meteor.user()) {
    // the user is logged in
    if (Meteor.user() && Meteor.user().profile.name) {
      // the name is already set
      this.redirect('/');
    } else {
      this.render();
  } else {
    // the user is not logged in
} else {
  // waiting for the user to be ready
}

【讨论】:

  • 是的!这行得通。我已经坚持了很长时间。这是我帮助他人的功能:Router.route('/account',{ fastRender: true, data:function(){ if( Meteor.user() && Meteor.user().profile.guest ){ Router.go( '/login'); } else { Router.go('/account'); } }, template:'screen', yieldTemplates: { 'account': {to: 'content'}, } });
【解决方案2】:

Pandark 有正确答案,想分享我的工作代码!

Router.route('/account',{
fastRender: true,
data:function(){

    if( Meteor.user() && Meteor.user().profile.guest ){
        Router.go('/login');
    } else {
        Router.go('/account');
    }
},
template:'screen',
yieldTemplates: {
    'account': {to: 'content'},
}
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多