使用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>

 

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