0

这是我目前正在使用的

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没有重新执行。

4

1 回答 1

0

看看如何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;
  }

  ...

}

我不完全明白为什么,但它现在有效。

于 2017-07-20T16:05:14.587 回答