如何将普通JS对象转换为Immutable集合?

时间:2017-08-03 14:13:59

标签: javascript reactjs redux react-redux immutable.js

我在Immutable集合的帮助下管理了一个州的部分。 例如,

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()

我还将状态保存在localStorage中,所以问题是从localStorage检索状态时我不知道如何将JS对象转换回嵌套集合(例如包含作为List的字段)。 我已经尝试使用Immutable.fromJS()方法,但显然它不适用于Record。有没有人面临同样的问题?请帮忙解决它

2 个答案:

答案 0 :(得分:1)

我认为您需要先将import {Component, Input} from '@angular/core' @Component({ selector: 'my-cool', template: ` cool {{text}} `, }) export class MyCoolComponent { @Input('text') text:String; constructor() { this.text = `test` } } 序列化,然后再将其设置为localStorage。从localStorage获取后,您可以使用JSON.stringify()

对其进行反序列化

答案 1 :(得分:1)

我使用transit-immutable-js lib取得了成功。

来自docs

" Transit是一种基于JSON构建的序列化格式,可提供更丰富的类型。它是可扩展的,这使其成为为Immutable类型轻松提供序列化和反序列化功能的不错选择。"

使用记录的示例:

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
相关问题