我应该将Meteor订阅放在跟踪器反应容器中的哪个位置?

时间:2016-03-28 21:14:00

标签: javascript meteor reactjs ecmascript-6

使用Meteor 1.3,我有一个包含跟踪器反应的反应组件。我将其设置为tracker-react github

上的示例
class TaskIndex extends TrackerReact(React.Component) {

  constructor() {
    super();
    this.state = {
      subscription: {
        tasks: Meteor.subscribe("tasks", Meteor.userId() )
      }
    }
  }

  componentWillUnmount() {
      this.state.subscription.tasks.stop();
  }

  getTasks() {
      return  Tasks.find().fetch()
  }

  render() {
   //... displays the tasks
  }

}

订阅传递当前用户以获取正确的任务。问题是,当我注销并且Meteor.userId()变为未定义时,订阅不会更新。在刷新页面之前,任务保持可见。当我登录时反之亦然:当Meteor.userId()变为有效时,不会出现任何任务。

如果我将订阅放在getTasks()方法中,如下所示,它的行为正确,但感觉不对。订阅是否应该采用其中一种生命周期方法?如何停止订阅,我是否需要?

  getTasks() {
      Meteor.subscribe("tasks", Meteor.userId() );
      return  Tasks.find().fetch()
  }

由于

2 个答案:

答案 0 :(得分:0)

通过github issues

向作者提供答案
  

嘿,是的,那是因为它在构造函数中运行一次   在安装组件之前。如果您想订阅   当组件被渲染时,它是被动的,它需要在   渲染块。

...或者在渲染块调用的某个函数中。

render() {
   Meteor.subscribe("tasks", Meteor.userId() )
   return (
      // some jsx
   )
}

答案 1 :(得分:0)

我已完成以下操作以根据主动登录的用户更新订阅。老实说,我总是遇到同样的问题,而且永远找不到一个"官员"回答。

var userIdTracker;

class TaskIndex extends TrackerReact(React.Component) {

    constructor() {

        super();

        userIdTracker = Tracker.autorun(() => {
            this.setState({
                subscription: {
                    tasks: Meteor.subscribe("tasks", Meteor.userId())
                }
            });
        });

    }

    componentWillUnmount() {
        // Make sure you stop the autorun or it will continue to exist
        userIdTracker.stop();
        this.state.subscription.tasks.stop();
    }

    getTasks() {
        return  Tasks.find().fetch()
    }

    render() {
        //... displays the tasks
    }

}