不可变对象

时间:2018-09-26 12:50:13

标签: javascript reactjs immutable.js

是否可以像这样使用immutablejs

模式

<form action="https://website.com/subscribe/paypal/silver/paypal_agreement.php" method="POST">
    <button type="submit" style="margin-top:10px;border: 0; background: transparent">
    <img src="https://website.com/wp-content/uploads/2017/05/paypal.png" style = "width:170px;" alt="submit" />
    </button>                                   
</form>

不可变Js

class PeriodModel {
    constructor(
        id,
        title,
    ) {
        this.id = id;
        this.title = title;
    }
}

export default PeriodModel;

还是不再不变?通常我会这样:

let immutable = Map(new PeriodModel(1, 'title!'));

请告诉我这是否是一种好的做法。

1 个答案:

答案 0 :(得分:1)

我不能说这是否是一个好习惯,但是您的做法似乎无效;它不会生成不可变的地图,而只会生成一个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将是一个普通的对象。