我试图用参数来实现计算的getter函数,比如如本答案所示和MobX 6以及相应版本的mobx-utils。
export class CodificatorStore {
@observable.ref items: Array<Codificator> | null = null;
@action setItems(items: Array<Codificator>): void {
this.items = items;
}
@computed get item(): ITransformer<number, Codificator | null> {
return createTransformer((index: number): Codificator | null => {
console.log(`get item by index: ${index}`);
return this.items ? this.items[index] : null;
});
}
}我期望创建函数来回忆录它的执行结果,每次我用相同的参数和相同的(没有改变的)可观察的items调用它,但是我在React组件的render方法中得到一个新的记录在每个调用上的消息:
codificatorStore.item(0);根据文档和源代码,我期望在所有连续调用时从reactiveView返回回传值,而不是调用我的转换函数。我是不是误解了什么?怎样才能达到预期的效果?
发布于 2021-12-21 13:25:04
首先,你真的需要回忆录这样简单的操作吗?还是只是个例子?
第二,如果你只需要回忆录,你根本不需要createTransformer,它的作用有点不同。但是您可以使用computedFn,就像这样:
import { computedFn } from 'mobx-utils';
// ...
item = computedFn((index) => {
console.log(`get item by index: ${index}`);
return this.items ? this.items[index] : null;
});https://stackoverflow.com/questions/70435314
复制相似问题