简体   繁体   English

如何将普通的JS对象转换为不可变集合?

[英]How to convert a plain JS object to an Immutable collection?

I have parts of a state managed with the help of Immutable collections. 我有一部分状态是在不可变集合的帮助下管理的。 For example, 例如,

const FolderModel = Record({
    id: null,
    name: '',
    items: List()
})

const DocsModel = Record({
    folder1: new FolderModel({
        id: 1,
        name: 'Избранное'
    }),
    folder2: new FolderModel({
        id: 2,
        name: 'Отложенное'
    }),
    folder3: new FolderModel({
        id: 3,
        name: 'Топ тендеры'
    })
})

const initialState = new DocsModel()

I also save my state in a localStorage , so the problem is when retrieve the state from localStorage I don't know how to convert JS object back to a nested collection (eg Record containing a field that is a List). 我也将状态保存在localStorage ,所以问题是从localStorage检索状态时,我不知道如何将JS对象转换回嵌套的集合(例如,Record包含一个List字段)。 I already tried using Immutable.fromJS() method but apparently it doesn't work for Record s. 我已经尝试过使用Immutable.fromJS()方法,但是显然不适用于Record Did anybody face the same problem? 有人遇到过同样的问题吗? Please help resolving it 请协助解决

I believe you need to serialize your collection with JSON.stringify() before setting it to localStorage. 我相信您需要JSON.stringify()序列化集合,然后再将其设置为localStorage。 After getting it back from localStorage you can deserialize it with JSON.parse() 从localStorage取回后,可以使用JSON.parse()反序列化

I've had success using the transit-immutable-js lib. 我已经成功使用了transit-immutable-js lib。

From the docs : 文档

"Transit is a serialisation format which builds on top of JSON to provide a richer set of types. It is extensible, which makes it a good choice for easily providing serialisation and deserialisation capabilities for Immutable's types." “ Transit是一种序列化格式,它建立在JSON之上,以提供更丰富的类型集。它是可扩展的,这使其成为轻松为Immutable的类型提供序列化和反序列化功能的理想选择。”

Example usage with Records: 记录的用法示例:

var FooRecord = Immutable.Record({ a: 1, b: 2, }, 'Foo'),
    foo = new FooRecord(),
    serialize = transit.withRecords([FooRecord]),
    json = serialize.toJSON(foo);

console.log(json); //=> json string of your data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM