首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tracker.autorun只运行一次

Tracker.autorun只运行一次
EN

Stack Overflow用户
提问于 2017-07-19 21:09:56
回答 1查看 203关注 0票数 0

下面是我目前正在做的工作

代码语言:javascript
复制
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不监视DB模型?为什么当DB发生变化时,函数不重新评估Collection.findOne

编辑**

在更新DB时,我确实看到了通过meteortoys:allthings进行的集合更改,但是autorun没有被重新执行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-20 16:05:14

看看tracker-react是如何实现它的,我修改了代码如下

代码语言:javascript
复制
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;
  }

  ...

}

我不完全明白为什么,但现在起作用了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45201057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档