"Cannot read property 'username' of undefined"在流星路线?

"Cannot read property 'username' of undefined" in a Meteor Route?

该页面仍按应有的方式呈现,但这出现在我的控制台日志中。

Exception in callback of async function: TypeError: Cannot read property 'username' of undefined at null. (http://localhost:3000/router.js?39194109cc7760190c519a386d66c807ba19230c:48:9) at boundNext (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:424:31) at Meteor.bindEnvironment (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22) at onRerun (http://localhost:3000/packages/iron_router.js?a427868585af16bb88b7c9996b2449aebb8dbf51:520:9) at boundNext (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:424:31) at Meteor.bindEnvironment (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22) at onRun (http://localhost:3000/packages/iron_router.js?a427868585af16bb88b7c9996b2449aebb8dbf51:505:11) at boundNext (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:424:31) at Meteor.bindEnvironment (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22) at dispatch (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:448:3)

指向下面指示的行:

var OnBeforeActions = {
  loginRequired: function() {
    if (!Meteor.userId()) {
      this.render('hello');
    } else {
      this.next();
    }
  }
};
Router.onBeforeAction(OnBeforeActions.loginRequired, {
  only: ['home']
});

Router.route('/', function() {
  // this.render('homepage');
  Router.go('/users/' + Meteor.userId());
});

Router.route('/users/:user_id', function() {
  this.render('home', {
    data: {
      username: Meteor.users.findOne({
        _id: this.params.user_id
      }).username, // THIS LINE HERE
    }
  });
});

我的想法是,如果用户已经登录,则将他重定向到他的页面 - 它似乎可以正常工作,但为什么我会收到这个?

当浏览器最初加载时,将没有任何可用数据(所有集合将是空的 - 直到它们被下载。因此查询 Meteor.users.findOne({_id: this.params.user_id}) 的结果将是 undefined

这就是您无法从 undefined 中读取 username 的原因。

由于查询 re-run/it 是反应式的,您只需要在它为 null 时考虑在内,它会自行解决。 user.username 仅在用户不是 null:

时才被读取
Router.route('/users/:user_id', function() {
  var user = Meteor.users.findOne({_id :this.params.user_id});
  this.render('home', {
    data: {
      username: user && user.username
    }
  });
});