我有以下动作和减速器:

动作:

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),但是似乎有很多方法来组织代码:


GET_NODES reducer打包到函数中,在OPEN_NODE中调用它,然后添加open:true
修改openNode动作,一起发送[OPEN_NODE, GET_NODES],但是怎么写switch(action.type)的大小写呢?
OPEN_NODE减速器调度getNodes动作来触发GET_NODES减速器


哪个最好?还是其他更好的方法?

最佳答案

您不必将所有内容保留在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);
  // ....
}

关于javascript - 写 Action 和Reducer高效而干净( react redux),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37941447/

10-16 19:50