Far*_*nir 5 javascript meteor iron-router
如果新用户注册,我将他们带到入门路线,这样他们输入就可以输入一个名称/gs.我将名称存储在当前用户的配置文件对象的name属性中.现在,如果已经输入名称并访问/gs路由的用户我想将它们重定向到根目录.在铁路由器中,我这样做:
Router.route('/gs', {
name: 'gs',
onBeforeAction: function() {
if ( Meteor.user().profile.name ) {
this.redirect('/');
} else {
this.render();
}
}
});
Run Code Online (Sandbox Code Playgroud)
即使这样可行,它也会向控制台输出2个错误.其中一个是"无法读取未定义的属性'配置文件"和缺乏this.next().任何解决这些问题的方法.
您的路由功能和大多数挂钩都在反应计算中运行.这意味着如果响应数据源发生更改,它们将自动重新运行.例如,如果在路由功能中调用Meteor.user(),则每次Meteor.user()的值发生更改时,路由功能都将重新运行.(Iron.Router Guide:Reactivity)
Hook函数和调度到路由时运行的所有函数都在一个被动计算中运行:如果任何被动数据源使计算无效,它们将重新运行.在上面的示例中,如果Meteor.user()更改,则将再次运行整组路由功能.(Iron.Router Guide:使用挂钩)
第一次运行该函数,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
}
Run Code Online (Sandbox Code Playgroud)