尝试读取属性时,meteor在浏览器控制台中出现TypeError: Cannot read property 'featuredImage' of undefined
错误。但是它显示为featuredImage
,网站运行正常。我怎样才能摆脱这个错误?是不是因为我的订阅尚未准备好?那是不是这样,如何解决? (PS:我正在使用流路由器,所以我不能等待路由器中的订阅)
我的模板代码:
Template.About.helpers({
page: () => {
return findPage();
},
featuredImage: () => {
var thisPage = findPage();
return Images.findOne({
"_id": thisPage.featuredImage
});
}
});
function findPage() {
return Pages.findOne({
slug: 'about'
});
}
路由器代码:
FlowRouter.route('/about', {
name: 'about',
subscriptions: function() {
this.register('page', Meteor.subscribe('pages', 'about'));
this.register('image', Meteor.subscribe('images'));
},
action() {
BlazeLayout.render('MainLayout', {
content: 'About'
});
setTitle('About Us');
},
fastRender: true
});
答案 0 :(得分:2)
订阅可能尚未准备好。 FlowRouter提供了一个处理这个问题的工具,你的助手应该是这样的:
Template.About.helpers({
page: () => {
// If you only need a specific subscription to be ready
return FlowRouter.subsReady('page') && findPage() || null;
},
featuredImage: () => {
// Ensure ALL subscriptions are ready
if ( FlowRouter.subsReady() ) {
var thisPage = findPage();
return Images.findOne({
"_id": thisPage.featuredImage // Probably should be thisPage.featuredImage._id
});
}
return null;
}
});
但是,为了获得最佳性能,您应该使用if (FlowRouter.subsReady('page') && Flowrouter.subsReady('image'))
而不是FlowRouter.subsReady()
,因为如果您有其他待处理的订阅量很大,即使您不需要它们,也会等待这些订阅。< / p>