写动作和减速器高效清洁(反应还原)

时间:2016-06-21 10:06:13

标签: javascript reactjs redux react-redux

我有以下行动和减速器:

动作:

import { OPEN_NODE, CLOSE_NODE, GET_NODES } from '../constants/NodeActionTypes';

export function openNode(path) {
  return {
    type: OPEN_NODE,
    path: path
  };
}

export function closeNode() {
  return {
    type: CLOSE_NODE
  };
}


export function getNodes(path) {
  return {
    type: GET_NODES,
    path: path
  };
}

减速器:

export default function opener(state = initialState, action) {
  switch (action.type) {
  case OPEN_NODE:
    var { path } = action
    var {nodes} = getFileList(path)
    return {
      ...state,
      open:true,
      nodes:nodes
    };
  case CLOSE_NODE:
    return {
      ...state,
      open:false
    };
  case GET_NODES:
    var { path } = action
    var {nodes} = getFileList(path)
    return {
      ...state,
      nodes:nodes
    };
  default:
    return state;
  }
}

显然,OPEN_NODE包含GET_NODES(仅加open:true),但似乎有很多方法来组织代码:

  1. GET_NODES缩减器打包到一个函数中,在OPEN_NODE中调用它,然后添加open:true

  2. 修改openNode操作,将[OPEN_NODE, GET_NODES]发送到一起,但如何撰写switch(action.type)的案例?

  3. OPEN_NODE reducer调度getNodes动作以触发GET_NODES减速器

  4. 哪个最好?或者任何其他更好的方式?

3 个答案:

答案 0 :(得分:1)

您不必将所有内容保留在switch语句中。如果你有2个类似的动作,只需重构为私有函数并调用它。

在您的情况下,它可能类似于:

// your reducer helper
const getNodes = (state) => {
 var { path } = action
 var {nodes} = getFileList(path)
 return {
   ...state,
   nodes:nodes
 };
};

// your reducer function
export default function opener(state = initialState, action) {
  switch (action.type) {
  case OPEN_NODE:
    return { ...getNodes(state), open:true };
  case GET_NODES:
    return getNodes(state);
  // ....
}

答案 1 :(得分:0)

您只需使用switch语句执行这两个操作:

export default function opener(state = initialState, action) {
  switch (action.type) {
  case OPEN_NODE:
  case GET_NODES:
    var { path } = action
    var {nodes} = getFileList(path)
    return {
      ...state,
      nodes:nodes
      open: action.type === OPEN_NODE ? true : state.open
    };
  case CLOSE_NODE:
    return {
      ...state,
      open:false
    };
  default:
    return state;
  }
}

答案 2 :(得分:0)

检出我的github项目,以创建通用reducer。我想要的解决方案将解决您当前遇到的许多问题。

Redux-Reducer-Generator