redux 初步理解

派发一个 action 给 reducer, reducer 生成了一个新的 state;

redux 通过 Store 来保存数据, store.getState 获得数据, 而要更新 state, 则需要 store.dispatch(action);

由于reducer 里才会生成一个新的 state, 所以 store 的创建必须是 store = createStore(reducer);

为了把 action 和 state 串起来,开发一些函数,这就是 reducer

reducer 只是一个接收 state 和 action,并返回新的 state 的函数。

 

const combineReducers = reducers => {

  return (state = {}, action) => {

    return Object.keys(reducers).reduce(

      (nextState, key) => {

        nextState[key] = reducers[key](state[key], action);

        return nextState;

      },

      {} 

    );

  };

};

 

const reducer = combineReducers({

  a: doSomethingWithA,

  b: processB,

  c: c

})

 

reducer 有3个属性 a,b,c   每个属性的值 reducer({state: a}).a ;;;;;;;;  reducer({state.b}).b

Action Creator 是一个函数,返回的是一个对象 { type:’add’,…. }

如果作为中间件, 返回的一个是一个函数 function(dispatch, getState){}

 

state

{

  todos: [{

    text: 'Eat food',

    completed: true

  }, {

    text: 'Exercise',

    completed: false

  }],

  visibilityFilter: 'SHOW_COMPLETED'

}

 

Action

{ type: 'ADD_TODO', text: 'Go to swimming pool' }

{ type: 'TOGGLE_TODO', index: 1 }

{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

posted @ 2017-08-11 22:44  zhengming  阅读(219)  评论(0编辑  收藏  举报