在 Immutable.js 中扩展记录

Extending Record in Immutable.js

我正在使用 Immuatable.js,我想扩展 Immutable.Record,所以我有一个 class,它的工作原理相同,但添加了一些默认属性和函数。

查看源代码,Record.js 是一个扩展 KeyedCollection 的 ES6 class,但 returns 来自构造函数的函数。

https://github.com/facebook/immutable-js/blob/master/src/Record.js

我不太明白这样做的副作用。

基本上我想要一个 FooRecord class 我可以在其中执行此操作:

class FooifiedRecord extends FooRecord({
  name: '',
}){
  sayMyName(){
    return this.name;
  }
};

这相当于:

class FooifiedRecord extends Immutable.Record({
  name: '',
  foo: '',
}) {
  doFoo(){
    return this.foo + ' bar';
  }
  sayMyName(){
    return this.name;
  }
}

但我不确定语法是否正确。

编辑:与 一点也不相似,涵盖了 Immutable.Record 的基本用法。我想知道如何扩展它。

如果你不打算用 new 实例化你的基础 class 你可以做 justinko recommends here:

import { Record } from 'immutable'

const Base = defaultValues => class extends Record({
  id: undefined,
  links: {},
  errors: {},
  ...defaultValues
}) {

}

class User extends Base({
  firstName: undefined,
  lastName: undefined
}) {
  fullName() {
    return this.firstName + ' ' + this.lastName 
  }
}