是否可以使用 immutablejs像这样:
模态
class PeriodModel {
constructor(
id,
title,
) {
this.id = id;
this.title = title;
}
}
export default PeriodModel;
ImmutableJs
let immutable = Map(new PeriodModel(1, 'title!'));
或者它不再是不可变的了吗?通常我会这样做:
let immutable = Map({ id: 1, title: 'title!'});
请让我知道这是否是好的做法。
最佳答案
我不能说这是好事还是坏事,但你的做法似乎行不通;它不会生成不可变映射,它只会生成 PeriodModel。
我向您的类添加了一个方法 toObject
,它返回类属性的普通对象。
class PeriodModel {
constructor(
id,
title,
) {
this.id = id;
this.title = title;
}
toObject() {
return {
id: this.id,
title: this.title
}
}
}
const periodMap = Immutable.fromJS(new PeriodModel(1, 'title!').toObject());
const periodMapWithoutMethod = Immutable.fromJS(new PeriodModel(1, 'title!'));
periodMap
将是一个不可变映射,但 periodMapWithoutMethod
将是一个普通对象。
关于javascript - 带对象的 ImmutableJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52518169/