gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 04:35:38 24 4
gpt4 key购买 nike

我想创建具有(或多或少)唯一键的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com