immutable是用來避免開發者直接修改state的庫。
我們首先要將state對象變爲immutable對象。使用fromJS方法。
import { fromJS } from 'immutable'
//使用immutable對象,是state數據不可變,是防止我們直接修改state數據的一個庫
const defaultState = fromJS({
fouced:false,
list:[]
});
當我們的state的對象變爲immutable對象後,我們修改state是就不能想之前那樣,我們需要調用immutable庫中提供的set()方法,
export default (state = defaultState,action) => {
if(action.type === actionTypes.CHANGE_FOCUSED) {
return state.set('fouced', true)
//原本是返回一個新的對象。現在把它變爲immutable對象後,需要使用set方法,它會自動返回一個新的對象
// {
// fouced:true
// }
}
而我們在mapStateToProps時獲取到的state數據,也不能直接獲取,我們需要使用immutable庫提供的get()方法
const initMapStateToProps = (state) => {
return {
//原本是直接獲取到fouced,現在變爲immutable對象後,需要使用get方法才能獲取到fouced屬性(1)
// 當使用了redux-immutable獲取combineReducers後,state就變成immutable對象,所以header也要使用get方法獲取(2)
fouced:state.get('header').get('fouced'),//(2)
list:state.get('header').get('list')
//1.fouced:state.header.fouced => fouced:state.header.get('fouced')(1)
}
};