我正在尝试了解 MobX 中的深度可观察性。
特别是,在下面的代码中,我希望每次运行 setCommentCountForPost
时都调用 autorun,但目前没有。
我该如何修复这段代码?而且,当我阅读包含帖子的列表时,在 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);
最佳答案
MobX 跟踪属性访问,而不是值
在您的示例中,autorun 函数仅跟踪 _posts,而不跟踪 _posts 的属性,因此如果您更改 _posts 值,跟踪函数将起作用
console.log(toJS(p.getPosts()))
工作是因为 toJS 函数为了将可观察值转换为正常值,它访问 _posts 的属性。
如果您希望 p.getPosts()
起作用,您应该迭代访问 _posts 的属性。
关于javascript - MobX 和深度可观察性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52011224/