美文网首页
8.使用Immutiable.js来管理store中的数据19-

8.使用Immutiable.js来管理store中的数据19-

作者: 你坤儿姐 | 来源:发表于2019-06-10 17:59 被阅读0次

代码见https://gitee.com/XiaoKunErGe/JianShu.git历史版本第9、10次提交

immutable库是facebook研发的,可以帮助我们生成一个immutable对象,这个对象不可变更

1.安装immutable

打开GitHub搜索immutable 点开### immutable-js / immutable -js
yarn add immutable

2.在header的reducer中引入immutable
import { fromJS } from 'immutable';
//immutable提供了一个fromJS方法把一个JS对象转化为immutable对象

设置默认值的方法改写成

const defaultState = fromJS({
  focused: false
});
3.将header的index中代码改写为如下格式
const mapStateToProps= (state)=>{
  return{
    // focused:state.header.focused
    //这时state.header对应的数据已经是immutable数据了,所以点调用focused就不合适了
    focused: state.header.get('focused')
  }
}

同样header中代码改写格式如下

export default (state = defaultState, action) => {
  if(action.type === constants.SEARCH_FOCUS){
    // return{
    //   focused: true
    // }
    //immutable对象的set方法,会结合之前immutable对象的值和设置的值,返回一个全新的对象
    return state.set('focused', true);
  }
  if(action.type === constants.SEARCH_BLUR){
    return state.set('focused', false);
  }
  return state;
};

规范写法

const mapStateToProps= (state)=>{
  return{
    focused: state.header.get('focused')
  }
}

这里state的值是最外层store中reducer里创建的,这时我们需要依赖一个第三方的模块儿叫做redux-immutable
yarn add redux-immutable
现在我们让combineReducers从redux-immutable中引用
import { combineReducers } from 'redux-immutable';
这时reducer里面的数据内容就是一个immutable类型的数据内容了

//redux提供的combineReducers可以把小的reducer合并起来
import {reducer as headerReducer} from '../commen/header/store';
//as是ES6的一个语法 这里是给reducer起一个别名headerReducer
const reducer = combineReducers({
  header: headerReducer
});
export default reducer;
这时会报错 屏幕快照 2019-06-11 10.19.29.png

是因为这时这里接收的state已经是immutable对象了,这种写法就不可以了所以改写如下

const mapStateToProps= (state)=>{
  return{
    focused: state.get('header').get('focused')
  }

immutable中还有getIn方法和上面方法是等价的

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

相关文章

  • 8.使用Immutiable.js来管理store中的数据19-

    代码见https://gitee.com/XiaoKunErGe/JianShu.git历史版本第9、10次提交 ...

  • vue项目架构优化

    vuex使用规范 把数据放在状态管理(store)里面数据和视图完全分离。数据逻辑放在store处理,用户交互放在...

  • 对Extjs中store的多种操作

    Store.getCount() Store.getCount()返回的是store中的所有数据记录,然后使用fo...

  • 安装vuex

    创建store文件——>index.js: 例子 挂载 在组件中获取store的 使用 存数据例子 使用 acti...

  • vuex状态管理工具的使用

    vuex使用介绍 使用步骤 下载vuex: npm i vuex -S 创建store实例, 实现数据管理 sto...

  • Vuex学习之实现商品列表页

    安装 使用步骤 创建store文件夹 在main.js中引入store 使用数据 在完成数据初步渲染之后在组件一种...

  • vuex心得

    一、store是一个状态管理工具 (vueX中只有唯一 一个store)用途 :存数据 取数据 改数据 把需要共享...

  • Vuex

    一、vuex之store 1、vuex 定义 管理状态 + 共享数据 ,在各个组件间管理外部状态 2、使用 a、引...

  • Redux和react-redux

    Redux 管理数据状态的js应用工具(状态管理工具) 创建store,创建reducer,帮助store管理更新...

  • Redux

    Redux这个npm包,提供若干API让我们使用reducer创建store,并能更新store中的数据或获取st...

网友评论

      本文标题:8.使用Immutiable.js来管理store中的数据19-

      本文链接:https://www.haomeiwen.com/subject/zbbzxctx.html