我有以下行动和减速器:
动作:
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
缩减器打包到一个函数中,在OPEN_NODE
中调用它,然后添加open:true
。
修改openNode
操作,将[OPEN_NODE, GET_NODES]
发送到一起,但如何撰写switch(action.type)
的案例?
让OPEN_NODE
reducer调度getNodes
动作以触发GET_NODES
减速器
哪个最好?或者任何其他更好的方式?
答案 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。我想要的解决方案将解决您当前遇到的许多问题。