- 這是一篇筆記,參考了阮一峯老師的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)
);