是否有一种标准方法可以在 Record
上定义惰性计算属性?当我访问计算属性时,它应该运行一个函数来计算值,然后缓存该值。例如,像这样的东西:
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;
}
最佳答案
只要您不需要它来“重新计算”,我认为这应该可以做到。
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
关于javascript - Immutable.js 记录中的惰性计算属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49286418/