是否有一种标准方法可以在Record
s上定义惰性计算属性?当我访问计算属性时,它应该运行一个函数来计算值,然后缓存该值。例如,像:
const UserRecord = Record({
firstName: '',
lastName: '',
get fullName() {
console.log('Ran computation');
return `${this.firstName} ${this.lastName}`;
},
});
const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck
我能得到的最接近的是定义getFullName()
方法,然后手动记忆计算出的值。即:
getFullName() {
if (!this._fullName) {
this._fullName = `${this.firstName} ${this.lastName}`;
}
return this._fullName;
}
答案 0 :(得分:1)
只要您不再需要它,重新计算"这应该是我想的。
const UserRecord = Record({
firstName: '',
lastName: '',
get fullName() {
console.log('Ran computation');
var value = `${this.firstName} ${this.lastName}`;
delete this.fullName;
Object.defineProperty(this, 'fullName', {
value: value
});
return value;
},
});
const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck