redux - 在 redux 中对同一个数据片进行操作的拆分 reducer

标签 redux store redux-thunk reducers redux-store

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

{
  // ...data

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

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

对于每个保修,我都有一个或多个与其关联的选项user.warranties 中的关系采用以下形式:保修=> [选项]

为了实现它,我将像这样组合我的 reducer :

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

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

现在,“问题”是 USER_WARRANTYUSER_OPTION 操作由同一个 reducer 处理,因为:

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

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

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

因此,warranties reducer 必须对这两个操作使用react,如下所示:

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
  }
}

我想将其拆分为两个 reducer ,保证选项,但仍然让它们对同一数据片进行操作。

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

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

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

其中 magicalCombine 是我找不到的函数。


我已经尝试过reduce-reducers ,但看起来第二个 reducer (options)从未真正到达,而且我实际上不确定它,因为我并不是试图实现平坦状态,而是实际上对同一个键进行操作。

最佳答案

reducer 是一个简单的函数,它接受 stateaction 并返回一个新的状态对象,所以我认为这会做你想要的事情..

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

关于redux - 在 redux 中对同一个数据片进行操作的拆分 reducer ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53611242/

相关文章:

javascript - 链接 redux 连接 mapStateToProps ,以访问 mapDispatchToProps 内的 props

extjs - 如何将 Ext5 组合框与数据绑定(bind)一起使用

java - 使用 Sharedpreferences 检索值

javascript - Connect 不能与 Redux-react 中的 StateLess 组件一起使用

javascript - 处理 redux-thunk 中的错误不仅仅是通知用户

javascript - 无法组合Reducers()

reactjs - redux-saga, TypeError : (0 , _effects.takeLatest) 不是一个函数?

reactjs - redux-observable - action$.ofType 不是函数

json - Extjs 4 : Render store data into Ext. form.Panel不使用MVC框架

javascript - 在 redux 中,当为调度编写 thunk 时, "next"和 "store.dispatch"之间有什么区别?