zoukankan      html  css  js  c++  java
  • react之路:使用immutable管理store中的数据

    github仓库地址:https://github.com/wanghao12345/react-book

    简介

    immutable可以将store中的数据封装成一个immutable对象,这个对象拥有get,set等方法,这样就可以通过这些方法对store中的数据进行管理

    使用

    1.安装immutable依赖

    npm install immutable --save 或者  yarn add immutable

    2.store中引入

    import { fromJS } from 'immutable'

    3.使用get方法

    在mapStateToProps中获取state数据时:

     1 /**
     2  * 将仓库的state映射到props(获取state)
     3  * @param state
     4  */
     5 const mapStateToProps = (state) => {
     6     return {
     7         // 没有使用immutable
     8         // focused: state.header.focused
     9         // 使用了immutable
    10         focused: state.header.get('focused')
    11     }
    12 }

    4.使用set方法

     1 import * as constants from './constants'
     2 
     3 import { fromJS } from 'immutable'
     4 
     5 // fromJS将一个js对象转化成immutable对象
     6 const defaultState = fromJS({
     7     focused: false
     8 })
     9 
    10 export default (state = defaultState, action) => {
    11 
    12     if (action.type === constants.SEARCH_FOCUS) {
    13         // 没有使用immutable
    14         // return {
    15         //     focused: true
    16         // }
    17 
    18         // 使用了immutable
    19         // immutable对象的set方法,会结合之前的immutable对象的值
    20         // 和设置的值,返回一个全新的对象
    21         return state.set('focused', true)
    22     }
    23 
    24     if (action.type === constants.SEARCH_BLUR) {
    25         // 没有使用immutable
    26         // return {
    27         //     focused: false
    28         // }
    29 
    30         // 使用了immutable
    31         return state.set('focused', false)
    32     }
    33 
    34     return state
    35 }
  • 相关阅读:
    MySQL单实例、多实例服务脚本
    Shell之case结构条件句
    Shell之函数
    Shell之条件测试
    Shell脚本数字比较与四则运算
    Shell之分支结构
    Shell之变量的数值计算与输入
    Shell之变量子串与变量替换
    表单和框架
    HTML部分标签和代码
  • 原文地址:https://www.cnblogs.com/wanghao123/p/11162431.html
Copyright © 2011-2022 走看看