【发布时间】:2016-01-20 04:54:46
【问题描述】:
我正在为我的 Meteor 应用实现发布/订阅架构。我还没有删除autopublish。我使用 React 和 kadira:flow-router 和 kadira:react-layout。它工作正常。
这是我的发布代码(/lib/publications.js 虽然我也尝试过使用/server/publications.js,但没有变化):
if (Meteor.isServer) {
Meteor.publish("games", function() {
return Games.find({});
});
Meteor.publish("game", function(gameId) {
return Games.find({_id: gameId});
});
Meteor.publish("messages", function(gameId) {
return Messages.find({gameId: gameId}, {sort: {createdAt: -1}});
});
}
当然,如果我在/server 中使用它,我不会添加if 语句。我像这样(/lib/routing.js)在路由器中订阅这些出版物:
user.route('/game/:id', {
name: 'game',
subscriptions: function(params, queryParams) {
this.register('messages', Meteor.subscribe('messages', params.id));
},
// ...
});
然后我像这样 (/client/components/pages/game_page.jsx) 在 React 组件中获取数据:
// ...
mixins: [ReactMeteorData],
getMeteorData: function() {
return {
messages: Messages.find({}).fetch()
}
},
// ...
我没有得到所有 gameId 等于传递参数的消息,而是得到来自所有游戏的所有消息。如果我删除发布/订阅并只要求这样的数据:
// ...
mixins: [ReactMeteorData],
getMeteorData: function() {
return {
messages: Messages.find({gameId: gameId}, {sort: {createdAt: -1}}).fetch()
}
},
// ...
它工作得很好。知道为什么吗?我想我错过了一些东西:关于发布/订阅本身或关于在路由器中使用订阅。
【问题讨论】:
-
gameId设置在哪里?我怀疑它最初是undefined,因此流星订阅了整个集合。由于它永远不会再取消订阅,即使稍后,响应式地再次运行相同的订阅,您也永远不会丢失这些集合条目。 -
取自路线。
/game/:id并作为params.id传递给订阅。如果我在this.register(...)之前console.log(params.id)它会正确返回 id。
标签: javascript mongodb meteor reactjs