使用redux-actions优化actions管理

redux-actions的api很少,有三个createAction(s)  handleASction(s)   combineActions

主要用到createAction去统一管理action,虽然会增加一些代码量,但可以统一管理action,对代码维护有很大方便。

项目是用的dva框架,这个跟框架无关,createAction完成的是执行了一个dispatch

使用之前:

dispatch({type:'products/asyncDecr',payload:1})

payload可以传递参数

使用之后:

increment() 

可以给方法increment({a:1,b:2})传入参数,参数会在加载到payload参数上,可以直接取出来使用。

具体用法:

安装:$ npm install redux-actions --save

使用:

新建action目录下index.js文件:

import { createAction } from 'redux-actions';

export const increment = createAction('products/increment');
export const decrement = createAction('products/decrement');
export const asyncDecr = createAction('products/asyncDecr');

UI component中使用:

首先引入组件:

import { increment, asyncDecr } from '../actions';

利用connect将actions连接到组件:

export default connect(mapStateToProps, { increment, asyncDecr })(ProductPage);

取出使用:

const { products, dispatch, increment, asyncDecr } = this.props;
<Button type="primary" onClick={()=>increment()}>increment</Button>&nbsp;&nbsp;
            <Button type="primary" onClick={()=>asyncDecr()}>asyncDecr</Button>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章