这是我的简化商店:
export class ProfileStore {
profile = {
id: 1,
name: "Tommy",
todos: [
{
value: "Clean the room",
done: false
}
]
};
constructor() {
makeObservable(this, {
profile: observable,
});
}
}
我的目标是聆听可观察到的“配置文件”中的每一个可能的变化。我想reaction
从 MobX 中使用它,但这有点棘手。
reaction(
() => this.profile,
() => {
console.log("change");
}
);
上面的例子根本不起作用,因为 MobX 不响应值,而是响应属性和引用。所以我把它改成这样:
reaction(
() => ({
id: this.profile.id,
name: this.profile.name,
todos: this.profile.todos.slice()
}),
() => {
console.log("change");
}
);
它开始工作,但并非完全正常。done
除了在 todos 中切换属性之外,它还会监听每一个变化。如果我添加另一个属性,我需要在这里列出,这有点乏味。
处理这个问题的最佳方法是什么?如何应对每一个可能的变化?
我为此制作了一个代码框:链接
尝试按下按钮并查看计数器。