2016-11-14

2016-11-14

redux学习笔记
- 每一个reducer函数都由两个参数state, action构成.其中state表示一个状态,即数据的状态.state!=undefined,表示要对state进行修改,并返回一个新的state. action表示一个操作,通常用type来进行区分,其它属性用于新state的属性分配.如以下代码:

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        name: action.name,
        completed: false
      };
    case 'TOGGLE_TODO':
      return state.id === action.id ?
        Object.assign({}, state, {
          completed: !state.completed
        }) :
        state;
    default:
      return state;
  }
};
  • 编写reducer时,能尽量分开的功能就尽量分来.一般来说,对数组操作的reducer,可以分成对单体和对整体操作两部分.如以下代码
const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        name: action.name,
        completed: false
      };
    case 'TOGGLE_TODO':
      return state.id === action.id ?
        Object.assign({}, state, {
          completed: !state.completed
        }) :
        state;
    default:
      return state;
  }
};
const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        todo(state, action)
      ];
    case 'TOGGLE_TODO':
      return state.map(t => {
        return todo(t, action);
      });
    default:
      return state;
  }
};
  • 当多个reducer有关联时,可以将它们进行合并.可以使用Redux的combineReducers({obj1, obj2});如以下代码
//合并reducer的手写实现 redux.combineReducers
const combineReducers = (reducers) => {
  return (state = {}, action) => {
    //Array.prototype.reduce(callback, initialValue);
    //callback四个参数, prev,cur,index,arr
    //initialValue表示设置的初始值
    return Object.keys(reducers).reduce((nextState, key) => {
      // console.log(nextState);
      nextState[key] = reducers[key](state[key], action);
      // console.log(nextState);
      return nextState;
    }, {});
  };
};
const todosApp = combineReducers({
  todos,
  visibilityFilter
});
  • redux思想跟react有相似之处。redux通过广播机制实现了对state tree的管理,而react通过自上而下的单向数据流实现了数据的传递。两者结合可以形成MV结构。react负责View的呈现,redux负责state的管理。

你可能感兴趣的:(javascript)