简书项目开发笔记5-immutable的使用

简介

immutable是facebook团队历时三年开发的一个库,利用immutable生成的对象,内容不可更改,它是不可直接赋值的对象,它可以有效的避免错误赋值的问题

使用

设置属性:

import { fromJS } from 'immutable';

const initialState = fromJS({
  focused: false
});

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.SEARCH_FOCUS:
      return state.set('focused', true);
    case actionTypes.SEARCH_BLUR:
      return state.set('focused', false);
    default:
      return state;
  }
}

export default reducer;

获得属性:

const mapStateToProps = (state, ownProps) => {
  return {
    focused: state.header.get('focused')
  }
}
const mapStateToProps = (state, ownProps) => {
  return {
    focused: state.getIn(['header', 'focused'])
  }
}

使用redux-immutable统一数据格式

将state转为immutable对象

import { combineReducers } from 'redux-immutable';

export default combineReducers({
  header: headerReducer
});
发布了15 篇原创文章 · 获赞 1 · 访问量 242

猜你喜欢

转载自blog.csdn.net/qiguoqi777/article/details/105382318
今日推荐