弄清原理之Redux combineReducers

Redux reducer的作用

只用来处理state 变化,返回新的state

//previousState是初始化的state
//经过reducer后,state变为nextState
const someReducer = (previousState, action) =>{
  return nextState;
}

reducer composition patten

reducer 组合模式---combineReducers的前身,直接看代码

const initialState = {
  count: 0,
  alert: { visible: false, message: '' }
};
const rootReducer = (state = initialState, action) => ({
  count: counterReducer(state.counter, action),
  alert: alertReducer(state.alert, action)
});
  • 拿一个总的rootReducer对象组合了两个countalert对象
    ,这时state tree里有{count:counterReducer返回的state,alert:alertReducer返回的state},由于state tree保存在store中,所以现有的state保存在了store中

combineReducers

做了那么多铺垫,现在说说combineReducers

1.是一种composition solution(前面提到过组合模式)的解决办法,合并多个reducers为一个reducer
2.返回的是一个对象,这个对象可看出state tree filed names和管理该state的reducer之间的映射
3.形式是:

import {combineReducers} from '../lib/redux';
import count from './count';
import alert from './alert';

const rootReducer = combineReducers({
  count:count
  alert:alert
});

export default rootReducer;

This combineReducer call translates to: "our state tree consists of two different properties, count and alert, which will be handled by the counter and alert reducers respectively".
4.手动实现combineReducers函数

import count from './count';
import alert from './alert';
//实现combineReducers函数
const combineReducers = (reducers) => {
  return (state = {}, action) => {
    return Object.keys(reducers).reduce((nextState, key) => {
       //key: count,key
       //state[key]:当前遍历的reducer先前的state值
       //nextState[key]:当前遍历的reducer变化后的state值
        nextState[key] = reducers[key](state[key], action);
        return nextState;
      }, {}); 
    };
};
//调用combineReducers,传入所有的reducers
const reducers = combineReducers({
    count,
    alert
})
export default reducers;

注意,reduce高阶函数第二个参数初始为{},遍历reducers的每个reducer,给nextState[key]赋值, 并push nextState到第二个参数{}中.

自己写了个demo

每天努力一点点
谢谢你看完


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容