javascript - 写 Action 和 reducer 高效且干净(react redux)

标签 javascript reactjs redux react-redux

我有以下操作和 reducer :

行动:

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
  };
}

reducer :

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 reducer 到一个函数,在 OPEN_NODE 中调用它,并添加open:true .

  2. 修改openNode行动,发送[OPEN_NODE, GET_NODES]在一起,但是怎么写switch(action.type)的情况?

  3. OPEN_NODE reducer dispatch getNodes触发操作 GET_NODES reducer

哪个最好?或者还有其他更好的方法吗?

最佳答案

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

就您而言,可能是这样的:

// 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/

相关文章:

ios - 呈现和关闭模式

javascript - 将过滤器属性传递给父组件

reactjs - 如何创建动态 typescript 类型 : The expected type comes from property 'type' which is declared here on type 'AppActions'

javascript - 如何动态地将类添加到焦点输入字段的父 div?

javascript - W3C/PhoneGap FileReader - 如何使用?

javascript - 使用触发器禁用右键单击上下文菜单以将其重新启用

javascript - 调用另一个模块函数作为回调 [ES6]

javascript - React props 未在 componentDidUpdate 中加载

javascript - 这是使用 createSelector 组合选择器的正确方法吗?

javascript - 使用正则表达式从字符串中提取值