Redux中reducer的二级拆分

javascript 代码

'use strict';
const Redux = require('redux');
const createStore = Redux.createStore;
const combineReducers = Redux.combineReducers;

/*reducers为一个对象,键值与store中state的键值相对应*/
/*合并reducers的内部简要处理逻辑*/
function combineRecucers(reducers) {
    return function(state, action) {
        /*返回一个全新的state*/
        let newState = {};
        /*进行处理*/
        for (let key in reducers) {
            newState[key] = reducers[key](state[key], action)
        }
        return newState;
    }
}

function aReducer(state = [], action) {
    console.log('a');
    switch(action.type) {
        case 'a': 
            /*应该返回一个全新的state*/
            return state.concat([action.data]);
        default: 
            return state;
    }
}

function bReducer(state = [], action) {
    console.log('b');
    switch(action.type) {
        case 'b': 
            return state.concat([action.data]);
        default: 
            return state;
    }
}

function cReducer(state = {name: '', group: []}, action) {
    console.log('c');
    switch(action.type) {
        case 'c': 
            /*return {
                name: cNameReducer(undefined, action),
                group: cGroupReducer(undefined, action)
            };*/
            /*对子state进一步进行reducer的拆分合并*/
            return combineReducers({name: cNameReducer, group: cGroupReducer})(state, action);
        default: 
            return state;
    }
}

function cNameReducer(state, action) {
    console.log('c1');
    if (state === undefined) return '';
    if (action.type === 'c') {
        return action.name;
    } else {
        return state;
    }
}

function cGroupReducer(state, action) {
    console.log('c2');
    if (state === undefined) return [];
    if (action.type === 'c') {
        return state.concat([action.item]);
    } else {
        return state;
    }
}

/*多个reducer需要与state结构相对应*/
const reducers = {
    a: aReducer, //会将store中state中的键值 'a' 对应的值传给函数 aReducer的第一个参数
    b: bReducer, //会将store中state中的键值 'b' 对应的值传给函数 bReducer的第一个参数
    c: cReducer
};

/*合并多个reducer为一个reducer*/
const reducer = combineReducers(reducers);

/*第二个参数为初始化store的state*/
const store = createStore(reducer, {
    a: [111],
    b: [222],
    c: {
        name: '',
        group: []
    }
});

/*一旦dispatch被触发,subscribe中注册的监听器也会触发*/
store.subscribe(() => {
    console.log(store.getState());  //获取store中的最新state
})

let action = {
    type: 'a',
    data: 'exwe'
};

let action2 = {
    type: 'c',
    name: 'roaming',
    item: 'code'
};

/*每一个dispatch都会将所有的reducer执行一遍*/
store.dispatch(action);
store.dispatch(action2);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值