- 想要把一个
JS对象
转换成immutable
的Map对象
怎么做呢。
- Map()
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()
是浅层的转换
- fromJS()
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
- 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()
})
}
}
}
小技巧
-
不要在Immutable对象中混用原生JavaScript对象;
-
基于上一点,当在Immutable对象内添加JavaScript对象时,先使用fromJS()将JavaScript对象转换成Immutable对象
// 不好
const obj = { key: value }
const newState = state.merge(obj)
// 较好
const obj = { key: value }
const newState = state.merge(fromJS(obj))
-
使用Immutable对象表示完整的Redux状态树;
对于一个Redux应用,完整的状态树应该由一个Immutable对象表示,而没有原生JavaScript对象。 -
容器组件可以使用react-redux提供的connect方法访问redux的store,所以我们需要保证选择器(selectors)总是返回Immutable对象,否则,将会导致不必要的重新渲染。另外,我们可以使用诸如reselect的第三方库缓存选择器(selectors)以提高部分情景下的性能。
网友评论