【问题标题】:MobX and deep observabilityMobX 和深度可观察性
【发布时间】:2018-08-24 20:20:19
【问题描述】:

我正在尝试了解 MobX 中的深度可观察性。 特别是,在以下代码中,我希望每次运行 setCommentCountForPost 时都会调用自动运行,但目前不是。

我应该如何修复此代码?而且,当我阅读包含帖子的列表时,可以在 Post 的属性上观察到足以激活自动运行? (就像我在自动运行中所做的那样)

我正在使用 MobX 5。

编辑:如果我在自动运行中使用以下调用,我发现代码工作正常:console.log(toJS(p.getPosts()));。 这很有趣,但是为什么,如果我只想调用 getPosts(),我应该怎么做?

这是代码

import { useStrict, configure, autorun } from 'mobx';
import { toJS, observable, action, computed } from 'mobx';


configure({ enforceActions: true });

class Post {
    @observable commentCount = 0;

    setCommentCount(c) {
        this.commentCount = c;
    }
}

class PostList {
    @observable _posts = {};

    @action createPost(id) {
        this._posts[id] = new Post();
    }

    @action setCommentCountForPost(id, c) {
        this._posts[id].setCommentCount(c);
    }

    getPosts() {
        return this._posts;
    }
}

let p = new PostList();
p.createPost(1);


autorun(function test () {
    console.log(p.getPosts());
});


p.setCommentCountForPost(1, 22);

【问题讨论】:

    标签: javascript mobx


    【解决方案1】:

    MobX 跟踪属性访问,而不是值

    在您的示例中,自动运行功能仅跟踪 _posts,但不跟踪 _posts 的属性,因此如果您更改 _posts 值,则跟踪功能将起作用

    console.log(toJS(p.getPosts())) 工作的原因是 toJS 函数为了将可观察值转换为正常值,它访问 _posts 的属性。

    如果您希望p.getPosts() 工作,您应该迭代访问_posts 的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2017-06-27
      • 1970-01-01
      相关资源
      最近更新 更多