0

私は3つの形式のレデューサーを見てきました:

// Form 1
function reducer(state, action) {
  if (state === undefined)
    return state = [];

  // handle action.type
  // ...
}

// Form 2
function reducer(state, action) {
  if (state === undefined)
    state = [];

  // handle action.type
  // ...
}

// Form 3
function reducer(state = [], action) {

  // handle action.type
  // ...
}

それらはすべて同じですか?Form 1 と Form 2 の違いは、Form 1 は何も見ても気にせずすぐに初期状態に戻ることaction.typeです。

また、フォーム 2 とフォーム 3 は、デフォルトのパラメーター値を使用してまったく同じであると思います。

主張は、公式のドキュメントや仕様によって立証できますか? つまり、レデューサーが初めて呼び出されたときはaction.type意味がありません。

4

3 に答える 3

0

単純に使用できます: createReducer from redux-starter-kit

これはマイクロソフトのこのデモでも使用されています

アクション タイプから、これらのアクション タイプを処理するケース レデューサー関数へのマッピングとしてレデューサーを定義できるユーティリティ関数。レデューサーの初期状態は、最初の引数として渡されます。

すべてのケース レデューサーの本体は、immer ライブラリからの Produce() の呼び出しで暗黙的にラップされます。つまり、新しい状態オブジェクトを返すのではなく、渡された状態オブジェクトを直接変更することもできます。これらのミューテーションは自動的かつ効率的にコピーに変換されるため、利便性と不変性の両方が得られます。

@param initialState — レデューサーによって返される初期状態。
@param actionsMap — アクション タイプからアクション タイプ固有のケース リデューサーへのマッピング。

使用法

export const LocalStorageReducer = createReducer<Store['localStorage']>(
  new LocalStorage(), // <= where you define the init value of this state
  {
    storeLocalStorageInput(state, action) {
      return state = {...state, [action.payload.item]: action.payload.value};
    },
    clearLocalStorageInput(state, action) {
      return state = new LocalStorage();
    },
  }
);

export const reducer = combineReducers({
  localStorage: LocalStorageReducer,
...

のタイプcreateReducer

(alias) createReducer<LocalStorage, CaseReducers<LocalStorage, any>>(initialState: LocalStorage, actionsMap: CaseReducers<LocalStorage, any>): Reducer<LocalStorage, AnyAction>
import createReducer

状態のサンプル

export class LocalStorage {
  /**
   * Editing plan id in planner pages
   */
  planId: string | undefined;
  /***
   * Touched id list
   */
  touchedIdList: Array<string>;
  constructor() {
    this.planId = undefined;
    this.touchedIdList = Array<string>();
  }
}

ライブラリによってこれらのことを行う方法がすでに開発されており、ほとんどの状況で手動で再度行う必要はありません。

于 2020-02-12T04:50:18.710 に答える