美文网首页
弄清原理之Redux combineReducers

弄清原理之Redux combineReducers

作者: 元气满满321 | 来源:发表于2017-04-25 16:50 被阅读316次

    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

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


    相关文章

      网友评论

          本文标题:弄清原理之Redux combineReducers

          本文链接:https://www.haomeiwen.com/subject/adblzttx.html