2019-04-08 immutable.js 构造Map对象

2019-04-08  本文已影响0人  KingAmo
  1. 想要把一个JS对象转换成 immutableMap对象怎么做呢。

Creates a new Immutable Map.
Note: Map is a factory function and not a class, and does not use the new keyword during construction.

Map() 是一个工厂函数,不是一个 class ,创建Map对象的时候不需要使用 new 关键字
Map() 是浅层的转换

Deeply converts plain JS objects and arrays to Immutable Maps and Lists.

深度的把 js对象 转换成immutable对象

他们的区别如下

      const obj = { key: { x: 1 } };
      const a = new Map(obj);
      const b = fromJS(obj);
      console.log(Map.isMap(a.get('key')); // false
      console.log(Map.isMap(b.get('key')); // true
  1. immutable对象转换成js对象

All Immutable.js Collections can be converted to plain JavaScript Arrays and Objects shallowly with toArray() and toObject() or deeply with toJS().

toArray()toObject() 是浅转换, toJS() 是深转换。

const deep = Map({ a: 1, b: 2, c: List([ 3, 4, 5 ]) });
console.log(deep.toObject()); // { a: 1, b: 2, c: List [ 3, 4, 5 ] }
console.log(deep.toArray()); // [ 1, 2, List [ 3, 4, 5 ] ]
console.log(deep.toJS()); // { a: 1, b: 2, c: [ 3, 4, 5 ] }
JSON.stringify(deep); // '{"a":1,"b":2,"c":[3,4,5]}'

React组件状态必须是一个原生JavaScript对象,而不能是一个Immutable对象,因为React的setState方法期望接受一个对象然后使用Object.assign方法将其与之前的状态对象合并

class  Component  extends React.Component {
    Constructor (props)  {
        super(props)

        this.state = {
            data: Immutable.Map({
            count:0,
            todos: List()
            })
        }
    }
}

小技巧

// 不好
const obj = { key: value }
const newState = state.merge(obj)

// 较好
const obj = { key: value }
const newState = state.merge(fromJS(obj))
上一篇 下一篇

猜你喜欢

热点阅读