2016-06-21 99 views
0

我有下面的动作和减速机:写入动作和减速高效,清洁(反应终极版)

操作:

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减速派遣getNodes动作来触发GET_NODES减速

这是最好的?或者有其他更好的方法?

+0

你基本上是问如何谱写自己的减速器。让我指出您正确的方向:https://egghead.io/courses/getting-started-with-redux。理解这门课程可以帮助你解决所有四个问题。 – xiaofan2406

回答

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

我不认为这是一个好方法。如果'OPEN_NODE'将来需要更多的状态,或者有一些调用'OPEN_NODE_2'需要一个新的状态'open2',那么代码会很糟糕,并且会充满'action.type === xxx? true:xxx' – Mithril

+0

如果你看到这种模式很多次,那么这是一个强有力的信号,你必须重构。但是对于您的具体使用情况,实际上并不是那么糟糕。 – Pcriulan

1

你不必让您的switch语句中的一切。如果您有两个类似的操作,只需重构一个私有函数并调用它即可。

在你的情况下,它可能是这样的:

// 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); 
    // .... 
} 
+0

是的,我认为选项1也不错,但是对选项2和3有什么想法?有什么优点和缺点? – Mithril