【发布时间】: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