在 redux 中对同一数据片进行操作的拆分减速器

问题描述 投票:0回答:1

我有一家商店,形状如下:

{
  // ...data

  user: {
    warranties: {
      W_1: ['O_1', 'O_2'],
      W_2: ['O_3', 'O_4']   
    }
  }
}

W_
开头的按键为保修,以
O_
开头的按键为选项。

对于每个保修,我都有一个或多个与其关联的选项

user.warranties
中的关系采用以下形式:
warranty => [options]

为了实现它,我将像这样组合我的减速器:

rootReducer = combineReducers({
  // ...other main reducers

  user: combineReducers({
    // ...other user reducers
    warranties
  })
})

现在,“问题”是

USER_WARRANTY
USER_OPTION
动作都由同一个reducer处理,因为:

  • 当我添加选项时,我需要将其推送到正确的保修条目。

  • 相反,当我添加保修时,我需要使用默认选项填充它。

  • 最终,它们对同一数据片进行操作

因此

warranties
减速器必须对这两个操作做出反应,如下所示:

export default function warranties(state = {}, action) {
  switch (action.type) {
    case USER_WARRANTIES_ADD:
    // add warranty key to `user.warranties`

    case USER_WARRANTIES_REMOVE:
    // remove warranty key from `user.warranties`

    case USER_OPTIONS_ADD:
    // push option to `user.warranties[warrantyID]`

    case USER_OPTIONS_REMOVE:
    // remove option from `user.warranties[warrantyID]`

    default:
      return state
  }
}

我想将其分成两个减速器,

warranties
options
,但仍然让它们在同一数据片上运行。

理想情况下,我会像这样编写我的根减速器:

rootReducer = combineReducers({
  // ...other main reducers

  user: combineReducers({
    // ...other user reducers
    warranties: magicalCombine({
      warranties,
      options
    })
  })
})

其中

magicalCombine
是我很难找到的功能。


我已经尝试过

reduce-reducers
,但看起来第二个减速器(
options
)从未真正达到,而且我实际上不确定它,因为我并没有试图实现平坦状态,而是实际上在相同的钥匙。

redux
1个回答
2
投票

reducer 是一个简单的函数,它接受

state
action
并返回一个新的状态对象,所以我认为这会做你想要的..

rootReducer = combineReducers({
  // ...other main reducers

  user: combineReducers({
    // ...other user reducers
    warranties: (state, action) => {
      // state is state.user.warranties
      // we pass it to each reducer in turn and return the result
      state = warranties(state, action);
      return options(state, action);
    }
  })
})

使用reduceReducers应该做同样的事情(我以前没有使用过它,但这就是它的样子..)

rootReducer = combineReducers({
  // ...other main reducers

  user: combineReducers({
    // ...other user reducers
    warranties: reduceReducers(warranties, options)
  })
})
redux 中的

combineReducers
只是有意限制为仅传递与提供给它的减速器对象中的键相匹配的状态属性的值,它在任何其他方面都没有什么特殊之处。在这里查看更多.. https://redux.js.org/recipes/structuringreducers/beyondcombinereducers

© www.soinside.com 2019 - 2024. All rights reserved.