使用redux-actions优化actions管理

redux-actions的api不多,有三个createAction(s)  handleASction(s)   combineActionsnpm

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

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

使用以前:框架

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

payload能够传递参数async

使用以后:this

increment() 

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

具体用法:code

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

使用:blog

新建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>
相关文章
相关标签/搜索