我有以下操作和 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
),但似乎有很多方法来组织代码:
包装
GET_NODES
reducer 到一个函数,在OPEN_NODE
中调用它,并添加open:true
.修改
openNode
行动,发送[OPEN_NODE, GET_NODES]
在一起,但是怎么写switch(action.type)
的情况?让
OPEN_NODE
reducer dispatchgetNodes
触发操作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/