immutable.js使用總結

1. immutable至關於 JSON.parse 和 JSON.stringify;redux

2.引入redux中,除了數組

在最外層 reducer中  import { combineReducers } from 'redux-immutable'; 函數

涉及到修改 (1)reducer 兩個文件  (2)組件ui

2.1 對於reducer:spa

首先對默認狀態:code

import { fromJS } from 'immutable';
const defaultState = fromJS({ 'requireFlag':true })

對於簡單的處理state,直接return便可:blog

case actionTypes.CHANGE_MORE_FLAG:
       return  state.set('requireFlag',!state.get('requireFlag'));

對於須要複雜處理的,通常將state傳入自定義函數,最後返回:get

export default (state=defaultState, action)=>{
  switch (action.type) {
    case actionTypes.INIT_LISTS:
      return handleInitList(state,action);
  }
}

const handleInitList = (state,action)=>{
    state.get('nav').map((item,index)=>{ //全部涉及到獲取state,使用get方法,這裏改變了state
      item.checked = false;
    });
    state.set('page',1);   //後續改變其餘值,單個是使用 state.set('page',1)
    return state.merge({   //改變多個值,須要使用merge函數,最後必定要 return出 merge函數
      activeIndex:action.tabIndex,
      cardId:action.cardId,
    })
    //return state;  不要使用merge以後,在這裏return state
}

 數組合並:string

 state.get('lifeRights').concat(action.initData.lifeRights); it

 

 

2.2 組件:

function mapStateToProps(state, ownProps) {
  return {
    userStatus:state.getIn(['bottom','userStatus']),  //注意此處有 中括號,第一個 reducer的名字
  } 
}

若是該reducer中 只有一層級,如reducer中的狀態定義爲:

 const defaultState = fromJS([]) 

則在組件中調用使用 get : rightsList: state.get('hotRight') 

相關文章
相關標籤/搜索