使用redux-actions重构redux实现的计数器
在很多Redux入门的文章里经常会用到计数器的示例,这里使用redux-action对redux实现的计数器做下重构,以便了解下redux-action的用法。
Redux实现的计数器
创建用于增减的两个Action
// ACTION
const COUNTER_INCREMENT = 'COUNTER_INCREMENT';
const COUNTER_DECREMENT = 'COUNTER_DECREMENT';
export const incrementCounter = () => ({
  type: COUNTER_INCREMENT,
});
export const decrementCounter = () => ({
  type: COUNTER_DECREMENT,
});
Redux实现的Action需要指定Action的类型
Reducer
export default (state = 0, action) => {
  switch (action.type) {
    case COUNTER_INCREMENT:
      return state + 1;
    case COUNTER_DECREMENT:
      return state - 1;
    default:
      return state;
  }
};
export const getCounter = state => state.counter;
Reducer会根据Action的类型在switch里执行不同的分支。
Redux-action重构计数器
首先需要安装redux-actions
$ npm install --save redux-actions
导入createAction和handleActions函数
import { createAction, handleActions } from 'redux-actions';
重构action
export const incrementCounter = createAction('COUNTER_INCREMENT');
export const decrementCounter = createAction('COUNTER_DECREMENT');
redux-actions使用createAction创建Action,参数为Action的类型。相对直接使用Redux创建简单很多。
重构Reducer
export default handleActions({
  [incrementCounter](state) {
    return state + 1;
  },
  [decrementCounter](state) {
    return state - 1;
  },
}, 0);
export const getCounter = state => state.counter;
redux-actions的reducer在handlActions里实现,这里使用了ES6计算属性,[incrementCounter]和[decrementCounter]分别对应于上面两个action。
总结
对比使用Redux直接实现的计数器,redux-actions使用函数式分别处理添加action和reducer,代码更精简,也更清晰
 
             
             
             
             
            