【问题标题】:Pass argument to pub function from React sub in Meteor?将参数从 Meteor 中的 React sub 传递给 pub 函数?
【发布时间】:2017-12-07 14:01:06
【问题描述】:

我正在发布我所有的 cmets 收藏:

Meteor.publish('comments', function() {
  return Comments.find(
    {},
    { fields: { date: 1, body: 1, user: 1, attachedTo: 1, attachedToID: 1 } },
  );
});

然后订阅一个 React 组件:

export default withTracker(() => {
  let commentsSub = Meteor.subscribe('comments');
  return {
    comments: Comments.find({}).fetch(),
  };
})(MyReactComponent);

到目前为止,这可行,但现在我想改进发送的 cmets。 cmets 的 attachTo 字段可以是“profile”或“homepage”。我已经修改了我的 pub 函数来接受输入:

Meteor.publish('comments', function(attachedTo) {
  return Comments.find(
    { attachedTo: attachedTo },
    { fields: { date: 1, body: 1, user: 1, attachedTo: 1, attachedToID: 1 } },
  );
});

但我看不到如何从我的 React 组件传递这个参数:

export default withTracker(() => {
  let commentsSub = Meteor.subscribe('comments');
  return {
    comments: Comments.find({ attachedTo: 'group' }).fetch(),
  };
})(MyReactComponent);

【问题讨论】:

  • 在您当前的实现中,发布函数中的attachTo 将是未定义的,因为您没有向它传递任何参数。 let commentsSub = Meteor.subscribe('comments','group'); 您必须将“组”作为参数传递给发布函数。

标签: reactjs meteor


【解决方案1】:

在您当前的实现中,发布函数中的 attachTo 将是未定义的,因为您没有向它传递任何参数。

订阅:

...
let commentsSub = Meteor.subscribe('comments','group'); // pass the value to the publish function.
...

您必须将“组”作为参数传递给发布函数。

【讨论】:

    【解决方案2】:

    我已经扩展了 blueren 的答案,因为我想命名参数:

    export default withTracker(() => {
      let commentsSub = Meteor.subscribe('comments', { attachedTo: 'profile' });
      return {
        comments: Comments.find({}).fetch(),
      };
    })(MyReactComponent);
    
    Meteor.publish('comments', function(attachedTo) {
      return Comments.find(
        { attachedTo },
        { fields: { date: 1, body: 1, user: 1, attachedTo: 1, attachedToID: 1 } },
      );
    });
    

    【讨论】:

    • 小注:{ attachedTo: 'profile' } -- 你正在传递对象。你的发布函数现在看起来像:Comments.find( { attachedTo: {attachedTo: 'profile'} }, .....我相信你只需要传递值,或者将查找查询更改为Comments.find( attachedTo, {fields.....})
    猜你喜欢
    • 2012-12-25
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2015-08-16
    相关资源
    最近更新 更多