在
MobX tutorial
一个示例对名为report的属性使用getter语法。
class ObservableTodoStore {
@observable todos = [];
@observable pendingRequests = 0;
constructor() {
mobx.autorun(() => console.log(this.report));
}
@computed
get completedTodosCount() {
return this.todos.filter(
todo => todo.completed === true
).length;
}
@computed
get report() {
if (this.todos.length === 0)
return "<none>";
return `Next todo: "${this.todos[0].task}". ` +
`Progress: ${this.completedTodosCount}/${this.todos.length}`;
}
addTodo(task) {
this.todos.push({
task: task,
completed: false,
assignee: null
});
}
}
const observableTodoStore = new ObservableTodoStore();
observableTodoStore.addTodo("read MobX tutorial");
observableTodoStore.addTodo("try MobX");
observableTodoStore.todos[0].completed = true;
observableTodoStore.todos[1].task = "try MobX in own project";
observableTodoStore.todos[0].task = "grok MobX tutorial";
// Next todo: "read MobX tutorial". Progress: 0/1
// Next todo: "read MobX tutorial". Progress: 0/2
// Next todo: "read MobX tutorial". Progress: 1/2
// Next todo: "grok MobX tutorial". Progress: 1/2
当我从报表属性中删除get关键字时,
@computed
report() {
// ...
然后更改对该报告的调用,以反映它不再是一个getter,
constructor() {
mobx.autorun(() => console.log(this.report()));
}
然后我仍然得到一个控制台输出。然而,这是非常不同的。
// Next todo: "grok MobX tutorial". Progress: 1/7
// Next todo: "grok MobX tutorial". Progress: 1/8
为什么结果如此不同?我认为决定使用getters更多的是一种风格选择。