zoukankan      html  css  js  c++  java
  • React-使用imutable.js来管理store中的数据

    reducer.js中store的数据是不能改变的,用原始的方法要手动的保证store不被修改,存在风险。imutable.js可以生成一个不可改变的对象,可以避免掉自己不小心修改掉store的情况。

    1.安装

    npm install immutable --save

    2.reducer.js中导入immutable,fromJS方法可以把一个普通对象变成不可变对象。修改数据时用set方法。

    import * as actionTypes from './actionTypes';
    import{ fromJS } from 'immutable'
    /*fromJS方法可以把一个普通对象变成不可变对象*/
    const defaultState=fromJS({
        focused:false
    })
    export default(state=defaultState,action)=>{
        if(action.type==actionTypes.SEARCH_FOCUS){
            //immutable对象的set方法,会结合之前的immutable对象的值和设置的值,返回一个全新的对象,不是修改对象的值
            return state.set('focused',true)
        }
        if(action.type==actionTypes.SEARCH_BLUR){
            return state.set('focused',false)
        }
        return state;
    }

    3.组件中获取数据时,用get方法。

    const mapStateToProps = (state) => {
        //focused是immutable对象,不能用state.header.focused的形式获取,要用get()
          return  {
              focused:state.header.get('focused')    
          }    
    }

     

  • 相关阅读:
    微信小程序用setData修改数组或对象中的一个属性值,超好用,最简单的实现方法,不容错过!大神们 都 在 看 的方法!!!
    pythonchallenge1
    pythonchallenge4
    pythonchallenge7
    pythonchallenge9
    pythonchallenge8
    pythonchallenge2
    pythonchallenge0
    递归排序
    pythonchallenge3
  • 原文地址:https://www.cnblogs.com/superlizhao/p/9474506.html
Copyright © 2011-2022 走看看