6

ReactJS アプリがTypeScriptあり、レデューサーを構築するためにredux使用しています。redux-toolkitアプリが大きくなったので、レデューサーのリファクタリングを開始したいと考えています。

私の還元状態は次のようになります。

{
  customers: Customers[],
  orders: {
    state1: SomeIndependentState1,
    state2: SomeIndependentState2,
    state3: SomeDependentState2,
    state4: SomeDependentState3,
  }
}

customersとのordersスライスは独立しているので、2 つの個別のレデューサーを簡単に作成して、combineReducers後で組み合わせることができます。

ordersここで、減速機をさらに分解したいと思います。

  • state1そしてstate2完全に独立しています。
  • state3からのデータに依存しますstate1
  • state4state1とからのデータに依存しますstate2

createReducerfrom redux-toolkit(またはツールキットの他の機能)を引き続き使用して、スライス内のネストされordersた各スライスのレデューサーを作成する方法はありますか?

のレデューサーを書き直し始めたordersので、これまでのところ次のとおりです。

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-toolkitが、チームがそれを使用しないようにするためには正当な理由が必要です。

4

1 に答える 1

1

必要なすべてをレデューサーに渡すだけです。この場合、、、などでordersはなく、状態全体を渡しますstate1state2state3

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. (これは上記の解決策に戻ります)。そうしないと、レデューサーは純粋な関数ではありません。

レデューサーについてあまり強調しないでください。それらは純粋な関数でなければなりませんが、任意の数と型の引数を持ち、何でも返すことができます。「関連する状態の小道具を関連する状態の小道具に」常に厳密に一致させる必要はありません。

于 2020-05-12T20:52:09.117 に答える