javascript – Immutable.js记录(默认)唯一ID

我想创建具有(或多或少)唯一键的Immutable.js记录.像这样的东西:

import { Record } from 'immutable'

var MyRecord = Record({
    key: Math.random().toString(),
    name: ""
})

这可能吗?我试过了,所有记录都有相同的密钥.我正在导入MyRecord,如下所示:

import { MyRecord } from '../model/MyRecord'

并创建这样的新记录

var r = new MyRecord(data)

其中data是json对象.

我当然可以在创建新记录后手动添加密钥,但我更愿意找到一种自动化方法.

最佳答案
感谢您提出的问题,感谢@robertklep引用我的答案:How to construct subclasses of Immutable.Record?

使用ids调整该答案略有不同:如果记录中有id,则不会生成一个.

这是唯一的改变.

// https://gist.github.com/jed/982883
// this can be any function that returns a string
function uuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)}

// this is the implementation you need
class MyRecordWithId extends Immutable.Record({
  id: '', // purposely have this empty string
  a: 'some a',
  b: 'some b'
}) {
  constructor(props) {
    super(Object.assign({}, props, {id: (props && props.id) || uuid()}))
  }
}

// this is a test to see the ID
const myRecord = new MyRecordWithId();
console.log('first record id: ', myRecord.id);

// these are tests to see if we can serialize the record and check if the ID is the same
const json = JSON.stringify(myRecord.toJS());
const js = JSON.parse(json);

const shouldHaveTheSameId = new MyRecordWithId().merge(Immutable.fromJS(js));

console.log('serialized id: ',shouldHaveTheSameId.id);

console.log('are the IDs the same?: ', myRecord.id === shouldHaveTheSameId.id ? 'yes' : 'no');

console.log('different id: ', new MyRecordWithId().id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>

转载注明原文:javascript – Immutable.js记录(默认)唯一ID - 代码日志