javascript - Immutable.js 具有(默认)唯一 ID 的记录

标签 javascript immutable.js

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

import { Record } from 'immutable'

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

这可能吗?我试过了,所有记录都有相同的 key 。我正在像这样导入 MyRecord:

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

像这样创造新的记录

var r = new MyRecord(data)

其中 data 是一个 json 对象。

我当然可以在创建新记录后手动添加 key ,但我更愿意找到一种自动执行此操作的方法。

最佳答案

感谢提出这个好问题,并感谢@robertklep 通过引用以下内容引导我找到这个答案:How to construct subclasses of Immutable.Record?

调整该答案以与 id 一起使用略有不同:如果记录中有一个 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 的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37854334/

相关文章:

javascript - 查找相交数组的列表

javascript - Javascript 中的舍入问题

javascript - 如何在剑道网格上进行计算?

react-native - mobx 和 Redux 的优缺点是什么,特别是在 React-Native 环境中?

javascript - 在与服务器通信时,将 Immutable.js 对象与 JSON 进行相互转换是否很常见

javascript - Jquery Ui 可排序项目选项仅选择第一项

javascript - 不同的网站图标加载?

javascript - 如何正确地传递 immutablejs 对象

javascript - 使用.map时如何获取不可变列表中的下一个元素?