使用immutable.js来管理store中的数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pansuyong/article/details/82939281

安装:

yarn add immutable

将state变为immutable对象,以防止state被改变

import { fromJs } from 'immutable'

fromJs 方法可以把一个js对象转化为一个immutable对象;

利用这个方法把state对象转化为immutable对象:

const defaultState=fromJs({
    focused:false
});

这个时候在header组件的index.js中对state中数据的调用方式

不能用  '.focused'的方式

const MapStateToProps=(state)=>{
return {
    focused:state.header.focused
}
};

而要变为:

 {
    focused:state.header.get('focused')
}

header组件下的store/reducer.js文件

import {SEARCH_FOCUS,SEARCH_BLUR} from './actionTypes';
import { fromJs } from 'immutable'
const defaultState=fromJs({
    focused:false
});

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

    return state
}

猜你喜欢

转载自blog.csdn.net/pansuyong/article/details/82939281