Tracker.autorun 只运行一次

Tracker.autorun only runs once

这是我目前正在使用的东西

class FooComponent extends Component {

  constructor(...args) {
    super(...args);

    this.state = {
      model: this.getModel()
    };
  }

  componentWillUnmount() {
    this._unmounted = true;
    this._modelComputation && this._modelComputation.stop();
    super.componentWillUnmount && super.componentWillUnmount();
  }

  getModel() {
    const model = {};

    this._modelComputation && this._modelComputation.stop();

    this._modelComputation = Tracker.autorun((computation) => {
      const { id } = this.props;
      const data = id && Collection.findOne(id);

      if (data) {
        Object.assign(model, data);
        !this._unmounted && this.forceUpdate();
      }
    });

    return model;
  }

  ...

}

不幸的是,反应模型不起作用,并且Tracker.autorun在数据库中更新模型时不执行函数。从文档来看,Collection.findOne 应该是反应式的,对吧?

我不确定我做错了什么。为什么 Tracker 不监控数据库模型?当数据库更改时,为什么函数不重新计算 Collection.findOne


** 编辑 **

更新数据库时,我确实通过 meteortoys:allthings 看到了集合更改,但是 autorun 没有重新执行。

看看 tracker-react 是如何实现它的,我像这样更改了我的代码

class FooComponent extends Component {

  constructor(...args) {
    super(...args);

    this.state = {
      model: this.getModel()
    };
  }

  componentWillUnmount() {
    this._unmounted = true;
    this._modelComputation && this._modelComputation.stop();
    super.componentWillUnmount && super.componentWillUnmount();
  }

  getModel() {
    const model = {};

    this._modelComputation && this._modelComputation.stop();

    this._modelComputation = Tracker.nonreactive(() => {
      return Tracker.autorun((computation) => {
        const { id } = this.props;
        const data = id && Collection.findOne(id);

        if (data) {
          Object.assign(model, data);
          !this._unmounted && this.forceUpdate();
        }
      });
    });

    return model;
  }

  ...

}

我不完全明白为什么,但现在可以了。