如何编写Redux Reducer?

时间:2015-10-21 18:33:59

标签: reactjs reducers redux

我有问题。 我有这个树视图(我的InitialState)。我该怎么写减速机, 那可见'属性更新,当我改变它。 例如,当我点击节点时,我想更新visible属性。

email: {
    folderList: [ {
        name: 'Inbox',
        isSelected: false,
        isNested: true,
        visible: false,
        folderList: [ {
                name: 'SubFolder1',
                isNested: true,
                visible: false,
                folderList : [ {
                    name: 'SubFolder2',
                    isNested: true,
                    visible: false,
                    folderList: [ {
                            name: 'SubFolder3',
                            isNested: false,
                            visible: false
                    } ],
                    count: 5
                } ]
            }, {
                name: 'SubFolder1',
                isNested: false,
                visible: false
        } ],
        icon: 'icon-icon_inbox',
        count: 44
    }, {
        name: 'Outbox',
        isSelected: false,
        isNested: false,
        icon: 'icon-icon_outbox',
        count: 0,
        visible: false
}

1 个答案:

答案 0 :(得分:1)

您应该规范化数据,以使商店看起来像:

{
  folders: {
    1: {
      name: 'Inbox',
      ...
      folderList: [2,3]
    },
    2: {
      name: 'Folder 1',
      ...
      folderList: [6,7]
    },
    3: {
      name: 'Folder 2',
      ...
      folderList: [8,9]
    },
    4: {
      name: 'Outbox',
      ...
    },
   ...
}

然后,当点击某个节点时,您的动作创建者将如下所示:

folderClicked(folderid) {
  return { type: 'SELECT_FOLDER', payload: { folderId, visible: true } }
}

你的减速器看起来像这样

const initialState = normalizedListOfFolders;

export function reducer(state = initialState, action) {
  switch(action.type) {
  case 'SELECT_FOLDER':
    const { folderId, visible } = action.payload;
    return { ...state, [folderID]: { ...state[folderId], visible: true } }
  default:
    return state;
}

如果你没有规范化,你将不得不用反应的不变性助手或immutable.js深入挖掘对象。