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精简代码之--actionType与redux-action-utils #11

Open
youngwind opened this issue Dec 19, 2015 · 0 comments
Open

redux精简代码之--actionType与redux-action-utils #11

youngwind opened this issue Dec 19, 2015 · 0 comments
Labels

Comments

@youngwind
Copy link
Owner

前言

用过redux的人都知道,action和actionType中都存在大量的重复代码。
(没有了解过redux的请移步这里


精简actionType

actionType是定义action常量的地方,一般长这个样。

exports.ADD_TAG = 'ADD_TAG';
exports.SELECT_REDDIT = 'SELECT_REDDIT';
exports.INVALIDATE_REDDIT = 'INVALIDATE_REDDIT';
exports.REQUEST_POSTS = 'REQUEST_POSTS';
exports.RECEIVE_POSTS = 'RECEIVE_POSTS';

使用keymirror之后变成这样。

var keyMirror = require('keymirror');
module.exports = keyMirror({
  ADD_TAG: null,
  SELECT_REDDIT: null,
  INVALIDATE_REDDIT: null,
  REQUEST_POSTS: null,
  RECEIVE_POSTS: null,
});

精简部分action

action是定义action返回数据的地方,有很多函数会长下面这个样。(当然,像那些异步请求那么复杂的除外)

exports.addTag = function (state) {
  return {
    type: types.ADD_TAG,
    state: state
  }
};
exports.selectReddit = function (reddit) {
  return {
    type: types.SELECT_REDDIT,
    reddit: reddit
  }
};

使用redux-action-utils之后长这个样。

var {actionCreator, optionsActionCreator}= require('redux-action-utils');
exports.addTag = actionCreator(types.ADD_TAG, 'state');
exports.selectReddit = actionCreator(types.SELECT_REDDIT, 'reddit');
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