Meteor.user()接收的自定义字段晚于_id、电子邮件和角色



与Meteor.user()中的其他字段相比,我有一个自定义字段"显示较晚"。这给我处理数据初始化带来了问题。我的问题是,为什么我的自定义字段显示得很晚?问题来了。

我为用户添加了一个自定义字段,如下所示:

if (Meteor.isServer) {
Meteor.publish('allusers', function() {
return Meteor.users.find({});
});  
Meteor.publish('userData', function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'lastViewedScenarios_id': 1 }});
} else {
this.ready();
}
});
}

在客户端上,我通过createContainer获取用户数据,如下所示:

export default AppContainer = createContainer(() => {
Meteor.subscribe('userData');
return {
currentUser: Meteor.user(),
};
}, App);

但当我看到页面加载时会发生什么时,我看到了以下行为:

第一次调用componentWillReceiveProps:

currentuser:
_id : "DNFNaecyNWGMe4HrZ"
emails : Array[1]
roles : Array[1] /* SOMETIMES present, sometimes not! */

仍在加载页面,随后调用componentWillReceiveProps:

currentuser:
_id : "DNFNaecyNWGMe4HrZ"
emails : Array[1]
roles : Array[1]
lastViewedScenarios_id :MongoID.ObjectID /* Never present until 2nd call! */

什么?我正在使用alanning:roles,也许这是在自定义发布userData。不管这是否是一个因素,我的自定义字段lastViewedScenarios_id只在currentuser的初始填充之后显示,尽管这些数据都在同一个Mongo集合中。

我的代码需要对当前用户数据的初始化采取行动,而这种"一次初始化一点"的行为使干净的逻辑在这里变得不可能。为什么会发生这种情况,除了为每个字段的存在添加大量丑陋的初始化和测试之外,我还能做些什么吗?

谢谢!

在组件调用componentWillReceiveProps时,确保数据完全可用的最安全方法是仅在userData订阅准备就绪时使用组件。这可以通过更改AppContainer:来实现

export default AppContainer = createContainer(() => {
const subscriptionHandler = Meteor.subscribe('userData');
return {
loading: !subscriptionHandler.ready()
currentUser: Meteor.user(),
};
}, App);

然后,在App组件中,您可以使用loading道具来决定仅在loading为false时才使用该组件。

类似这样的东西(在你的应用程序的render()方法中):

{
this.props.loading ? 
<div>Loading...</div> :
<CleanLogicComponent user=this.props.currentUser />
}

然后,当调用CleanLogicComponentcomponentWillReceiveProps时,所有用户数据都将可用。

最新更新