Reactjs 使用createReducer时在切片缩减器之间共享数据
我在Reactjs 使用createReducer时在切片缩减器之间共享数据,reactjs,react-redux,redux-toolkit,Reactjs,React Redux,Redux Toolkit,我在TypeScript中有一个带有redux的ReactJS应用程序,我正在使用redux工具包构建我的还原程序。随着应用程序越来越大,我想开始重构我的还原程序 我的redux状态如下所示: { customers: Customers[], orders: { state1: SomeIndependentState1, state2: SomeIndependentState2, state3: SomeDependentState2, state4
TypeScript
中有一个带有redux
的ReactJS应用程序,我正在使用redux工具包
构建我的还原程序。随着应用程序越来越大,我想开始重构我的还原程序
我的redux状态如下所示:
{
customers: Customers[],
orders: {
state1: SomeIndependentState1,
state2: SomeIndependentState2,
state3: SomeDependentState2,
state4: SomeDependentState3,
}
}
客户
和订单
切片是独立的,我可以很容易地为它们编写两个单独的还原器,稍后将它们与组合还原器
组合
现在,我想进一步细分我的订单
state1
和state2
是完全独立的李>
state3
取决于来自state1
的数据
state4
取决于state1
和state2
中的数据
是否有方法继续使用redux工具箱中的createReducer
(或工具箱中的一些其他功能)为orders
切片中的每个嵌套切片创建reducer
当我开始为订单
重新编写减速机时,以下是我迄今为止所做的:
export const ordersReducer = (state: Orders, action: AnyAction) => {
return {
state1: state1Reducer(state?.state1, action),
state2: state2Reducer(state?.state2, action),
state3: {}, // not sure how to write a reducer for this slice and satisfy its dependency on state1
state4: {}, // not sure how to write a reducer for this slice and staisfy its dependency on state1 and state2
}
};
const initialState1: State1 = {};
export const state1Reducer = createReducer(initialState1, (builder) =>
builder
.addCase(...)
.addCase(...)
);
const initialState2: State2 = {};
export const state2Reducer = createReducer(initialState2, (builder) =>
builder
.addCase(...)
.addCase(...)
);
注意:我无法控制redux状态的结构。我并不完全依赖于使用redux工具包
,但我需要一个很好的理由让我的团队远离它。只要将它需要的一切传递给reducer即可。在这种情况下,我将传递整个订单
状态,而不是传递state1
、state2
、state3
等
export const ordersReducer = (orders: Orders, action: AnyAction) => {
return {
// ...
state3: state3Reducer(orders, action),
// ...
}
};
const initialState3: State3 = {};
export const state3Reducer = createReducer(initialState3, (builder) =>
builder
.addCase(someAction, (orders, action) => orders.state3 + orders.state1) // or anything else
.addCase(...)
);
我将state
重命名为orders
。我知道规范文档经常使用state
,但这很快就会变得非常混乱
当然,如果state3
依赖于旧的state1
,则会出现这种情况。如果它取决于新值,那么您必须拥有state3
操作所需的所有数据以及旧的state1
。(这又回到了上述解决方案)。如果不这样做,那么减缩器就不是纯函数
不要过分强调你的减速机。它们必须是纯函数,但它们可以有任意数量和类型的参数并返回任何内容。他们不必总是严格地将“相关州道具与相关州道具”匹配起来。你所说的依赖于州1和州2是什么意思。你能举个例子吗为了计算state3,我需要动作有效载荷和state2中存储的数据的信息。state3=state3Reducer(state?.state3,action,state2)。不幸的是,这不太有效。createReducer是redux toolkit中的一个实用函数,它不接受完整状态。所以我不能直接向它下达命令。我最终创建了一个包装器函数,该函数接受完整状态,并使用适当的切片在内部调用createReducer。我使用变量作用域来访问完整状态。