Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

redux组织代码之:分割action #25

Open
youngwind opened this issue Jan 21, 2016 · 0 comments
Open

redux组织代码之:分割action #25

youngwind opened this issue Jan 21, 2016 · 0 comments
Labels

Comments

@youngwind
Copy link
Owner

前言

刚刚开始用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)
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant