如何在单个提供程序中为多个状态对象实现React useReducer

时间:2020-06-15 16:32:45

标签: javascript reactjs react-hooks use-reducer

我们在一个提供程序中具有三个相关但独立的巨型状态对象,并且不确定哪种方法更好地实现useReducer。

我们正在使用useReducer进行迁移,并且很难将它们全部保留在单个initialState中。

const initialStateA = {
  ...
}

const initialStateB = {
  ...
}

const initialStateC = {
  ...
}

选项1::一个“ mainReducer”来管理所有内容

const mainReducer = ({reducerA, reducerB, reducerC}, action) => {
  // reducerA + reducerB + reducerC....
}

const [state, dispatch] = useReducer(mainReducer, {...initialStateA, ...initialStateB, ...initialStateC})

选项2:具有三个单独的useReducers

const [stateA, dispatchA] = useReducer(reducerA, initialStateA)
const [stateB, dispatchB] = useReducer(reducerB, initialStateB)
const [stateC, dispatchC] = useReducer(reducerC, initialStateC)

哪种方法更好?每种优点/缺点是什么?或者两者之间几乎没有/没有区别?

1 个答案:

答案 0 :(得分:0)

如果这三个巨大的状态对象无法相互通信,并且每个对象将在不同的子应用程序中使用,那么我将按照redux style guide - Only One Redux Store Per App的建议将化简器拆分为单独的提供程序