Redux中計算新state的方法爲什麼被起名爲reducer?

  • 這是一篇筆記,參考了阮一峯老師的redux入門教程
/**
 * Reducer: 純函數!
 * 爲什麼這個函數叫做 Reducer 呢?
 * 因爲它可以作爲數組的reduce方法的參數。
 */

const reducer = (state = 0, action) => {
  switch (action.type) {
    case 'ADD':
      return state + action.payload;
    default: 
      return state;
  }
};

// 數組actions表示依次有三個 Action
// 分別是加0、加1和加2。
const actions = [
  { type: 'ADD', payload: 0 },
  { type: 'ADD', payload: 1 },
  { type: 'ADD', payload: 2 }
];

// 數組的reduce方法接受 Reducer 函數作爲參數
// 就可以直接得到最終的狀態3。
console.log(
  actions.reduce(reducer, 0)
);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章