【发布时间】:2018-03-14 19:40:44
【问题描述】:
有没有标准的方法来定义Records 上的惰性计算属性?当我访问计算属性时,它应该运行一个函数来计算值,然后缓存该值。例如,类似:
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;
}
【问题讨论】: