gpt4 book ai didi

javascript - 为什么在这个 MobX 示例中需要 'get'

转载 作者:行者123 更新时间:2023-11-30 14:50:42 26 4
gpt4 key购买 nike

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() {
// ...

然后更改对该报告的调用以反射(reflect)它不再是 setter/getter ,

constructor() {
mobx.autorun(() => console.log(this.report()));
}

然后我仍然得到控制台输出。然而,这是非常不同的。

// Next todo: "grok MobX tutorial". Progress: 1/7
// Next todo: "grok MobX tutorial". Progress: 1/8

为什么结果如此不同?我认为使用 setter/getter 的决定更多是一种风格选择。

最佳答案

您需要结合使用 get@computed 装饰器。

computed decotator 的文档指出:

If you have decorators enabled you can use the @computed decorator on any getter of a class property to declaratively created computed properties.

关于javascript - 为什么在这个 MobX 示例中需要 'get',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48143703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com