redux组织代码之:分割action
youngwind opened this issue · 0 comments
youngwind commented
前言
刚刚开始用redux的时候因为应用比较小,而且是单枪匹马,所以所有的action都写在一个action.js里面。后来随着应用的膨胀以及多人协作,这样显然是不行的。所以,应该像分割reducer那样分割action.
#1. action
// postAction.js
// 点击刷新按钮
exports.invalidateReddit = function (reddit) {
return {
type: types.INVALIDATE_REDDIT,
reddit: reddit
};
};
/**
* 根据文章类型发出请求
* @param reddit {string} 文章的类别 reactjs/frontend
* @returns {{type: null, reddit: *}}
*/
exports.requestPosts = function (reddit) {
return {
type: types.REQUEST_POSTS,
reddit: reddit
};
};
……
// numberAction.js
import {actionCreator} from "redux-action-utils";
import types from "../constants/ActionTypes.js";
exports.addTag = actionCreator(types.ADD_TAG, "state");
合成的action
// rootAction.js
import * as post from "./postAction.js";
import * as number from "./numberAction.js";
module.exports = {
post: post,
number: number
};
#2. 在container上应用他们
之前在container上绑定dispatch到action的时候是这样写的。
import action from "../action/action.js";
function mapDispatchToProps(dispatch) {
return {
action: bindActionCreators(action, dispatch),
};
}
现在因为action是组合的action,所以大概要写成这个样子。
import actions from "../action/rootActions.js";
function mapDispatchToProps(dispatch) {
return {
postActions: bindActionCreators(actions.post, dispatch),
numberActions: bindActionCreators(actions.number, dispatch)
};
}