使用 ImmutableJS Record 创建具有不同属性的子类

Create subclasses with different attributes using an ImmutableJS Record

我们使用 ES6 和 immutable.js 来创建不可变的 类。

class Animal extends Record({foo: ""});

我如何继承 Animal 并添加自定义属性,但仍然能够将其用作不可变 Record

class Animal extends Animal {}; // How to add the key "bar"?

Record 方法将创建的类型锁定到 defaultValues,不能用于进一步扩展属性。这是我提到的抱怨之一

如果你不太热衷于在运行时检查继承(instanceof),那么你可以这样做-

let foo = {foo: ""};
class Animal extends Immutable.Record(foo){}
let bar = {bar: ""};
class Mammals extends Immutable.Record(Object.assign({}, foo, bar)){}

虽然不能替代真正的继承,但它可以让您稍微重用模式。方法不会以这种方式被继承。

我们可以在这里使用mixins。



    const PersonMixin = Base => class extends Base {
        grew(years) {
            return this.set("age", this.age + years);  //returns a new Person, which is fine
        }
    };

    const PersonBase = PersonMixin(new Immutable.Record({name: null, age: null}));
    class Person extends PersonBase {}

    const AcademicanBase = PersonMixin(new Immutable.Record({name: null, age: null, title: null}));
    class Academician extends AcademicanBase {
        constructor({name, age, title}) {
            super({name, age, title});
        }
    }

    var a = new Academician({name: "Bob", age: 50, title: "Assoc. Prof"});
    console.log(a);
    console.log(a.grew(10).age); //grew works
    a.title = "Prof";   //the error "Cannot set on an immutable record" received.

我已经完成了这个,希望它会对某些人有所帮助。

// @flow
import type {RecordFactory, RecordOf} from "immutable";
import {Record} from "immutable";

type OneProps = {|
    key: boolean
|};
const oneDefaults: OneProps = {
    key: false
};
type One = RecordOf<OneProps>;
const oneItemBuilder: RecordFactory<OneProps> = Record(oneDefaults);

type TwoProps = {|
    ...OneProps,
    moreKeys: string
|};
const twoDefaults: TwoProps = {
    ...oneDefaults,
    moreKeys: "more"
};
type Two = RecordOf<TwoProps>;
const twoItemBuilder: RecordFactory<TwoProps> = Record(twoDefaults);

const oneItem: One = oneItemBuilder();
const twoItem: Two = twoItemBuilder({moreKeys: "more keys"});