直接使用redux,要写很多样板代码,大量的actiontype,actionCreator。
一个异步的方法要写三个actiontype,三个actionCreator,十分繁琐。
下面是本人使用的一种简化写法,使用数组动态生成一些action和actionCreator,具有参考价值。
action-type.js
export const asynctypes = [ 'getCateList', 'getArticleList', 'searchArticles', 'getArticleDetail', ] export const synctypes = [ '@@router/LOCATION_CHANGE' ] export const types = {}; asynctypes.forEach(item => { types[item + '.start'] = item + '.start'; types[item + '.ok'] = item + '.ok'; types[item + '.error'] = item + '.error'; }); synctypes.forEach(item => { types[item] = item; });
synctypes生成同步的actiontype,asynctypes生成异步的actiontype,字符串只在数组中声明一次,减少书写量
action.js
import {asynctypes} from './action-type'; import {createAction} from 'redux-actions'; function fCreateActionsAsync(aType,fCreateAction){ const oResult = {}; aType.forEach(item => { oResult[item + 'Start'] = fCreateAction(item + '.start'); oResult[item + 'Ok'] = fCreateAction(item + '.ok'); oResult[item + 'Error'] = fCreateAction(item + '.error'); }); return oResult; } export default fCreateActionsAsync(asynctypes,createAction);
导出的是通过asynctypes生成的三个actionCreator的集合,此集合可以直接在bindActionCreators函数中直接使用,
在组件中可以直接调用生成的action方法:
组件article.jsx
import acts from 'index/redux/actions'; export default connect( (state,props) => { return {data: state.article.data,currentCate:fCurrentCate(state,props)} }, dispatch => { return {actions: bindActionCreators(acts,dispatch)} } )(Article);
在组件中使用actions.getCateListStart就可以开始一个异步调用了。
start是个开始,项目中使用了redux-saga来自动唤起下面的异步调用,异步完成后自动调用ok或error的action。
//根saga中监控所有的异步调用 export default function* rootSaga(){ yield [ fork(wacthArticleDetail), fork(watchCateList), fork(watchActicleList), fork(watchSearchAtricles) ] } //监控到异步start调用,自动唤起异步调用 function* wacthArticleDetail(){ yield takeEvery(actions.getArticleDetailStart,fGetArticleDetailAsync); } //异步调用结束自动唤起Ok或者error的action function* fGetArticleDetailAsync(action) { try{ const articleId = action.payload.articleId; const article = yield call(getArticleDetail,articleId); yield put(actions.getArticleDetailOk(article)); } catch(err){ yield put(actions.getArticleDetailError(err)) } }