什么是immutable Data?
Immutable Data 就是一旦创建,就不能再被更改的数据。对 Immutable 对象的任何修改或添加删除操作都会返回一个新的 Immutable 对象。Immutable 实现的原理是 Persistent Data Structure(持久化数据结构),也就是使用旧数据创建新数据时,要保证旧数据同时可用且不变。同时为了避免 deepCopy 把所有节点都复制一遍带来的性能损耗,Immutable 使用了Structural Sharing(结构共享),即如果对象树中一个节点发生变化,只修改这个节点和受它影响的父节点,其它节点则进行共享。
immutable的使用:
1、安装
npm i immutable redux-immutable
2、在store/index.js中,构建store模块
import { createStore } from 'redux'
import rootReducers from './rootReducers';
const store = createStore( rootReducers )
export default store
3、在store文件夹下构建reducers
import { combineReducers } from 'redux-immutable';
import count from './count/reducers'
const rootReducers = combineReducers({
count
})
export default rootReducers
4、打造redux数据包
//state.js
//使用从immutable中解构出来的Map模块定义数据
import { Map } from 'immutable'
const state = Map({
count: 0
})
export default state
//分片的reducers.js
import state from './state'
import * as type from './type'
const reducers = ( newState = state, action ) => {
switch ( action.type ) {
case type.INCREMENT:
//数据操作
// newState immutable对象
return newState.set('count', newState.get('count') + 1 )
break;
default:
return newState
break;
}
}
export default reducers
//actionCreator.js
import * as type from './type'
const actionCreators = {
increment () {
const action = {
type: type.INCREMENT
}
return action
}
}
export default actionCreators
5、在组件中使用
import React ,{ Component } from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import actionCreators from '../store/count/actionCreators'
class Content extends Component {
render(){
return (
<div>
<button onClick ={this.props.increment} >+</button>
<p> count: {this.props.count.get('count')}</p>
</div>
)
}
}
//组件通过props获取属性,在connect的第一个参数的回调函数里,需要使用getIn()方法,否则组件内直接获取数据报错
export default connect( state => ({
count: state.getIn(['count'])
}) ,dispatch => bindActionCreators(actionCreators,dispatch)
)(Content)
immutable的使用心得
1.在没有使用Immutable之前操作store对象型数据的时候在不想修改原数据的时候通常的做法是复制一份,在复制的数据上做更新修改操作;但是每次deep-copy都要把整个对象递归的复制一份,如果遇到很复杂的对象型数据时,这样性能会很差;而现在使用了Immutable,当我们做一个set操作的时候,Immutable.js只修改这个节点和受它影响的父节点,其它节点则进行共享,可以大大提高性能;
2.在react中的shouldComponentUpdate方法中,判断组件是否需要更新的时候;对于复杂的对象型数据,去对比两个对象的值是否相等是很麻烦的;而Immutable提供了 is方法,去判断两个Immutable对象值是否相等;
3.由于Immutable提供了丰富的API,对于操作复杂的数据结构也变得很直观和方便;