一.什么是redux-actions

   redux-actions是一个简化action和reducer创建的一个封装库,里面有5个js文件,

   createAction.js

   handleAction.js

   handleActions.js

   index.js

   ownKeys.js

二.怎么使用?下面将从源码一一解释每个文件的的用处

  1.createAction.js

    从名字就可以看出,这是用来创建action的.其源码如下:

      

 1 /**
 2  * 参数不是function调用此函数
 3  */
 4 function identity(t) {
 5   return t;
 6 }
 7 
 8 /**
 9  * 创建action
10  * @param type  action的类型
11  * @param actionCreator 需要创建的action,函数
12  * @param metaCreator   action的属性
13  * @returns {Function}
14  */
15 export default function createAction(type, actionCreator, metaCreator) {
16     /**
17     * finalActionCreator最终创建的action,
18     * 判断传进来的参数是不是function,true返回这个函数,false调用identity函数
19     */
20   const finalActionCreator = typeof actionCreator === 'function'
21     ? actionCreator
22     : identity;
23   /**
24    * 返回一个匿名函数
25    */
26   return (...args) => {
27     /**
28      *创建的action,只有两个属性
29      */
30     const action = {
31       type,
32       payload: finalActionCreator(...args)
33     };
34     /**
35      * 如果给匿名函数传递参数的长度为1个,或者第一个参数元素的类型为Error,那么这么action的error属性为true
36      */
37     if (args.length === 1 && args[0] instanceof Error) {
38       // Handle FSA errors where the payload is an Error object. Set error.
39       action.error = true;
40     }
41     /**
42      * 传递到action里面的函数
43      */
44     if (typeof metaCreator === 'function') {
45       action.meta = metaCreator(...args);
46     }
47 
48     return action;
49   };
50 }
View Code

相关文章: