LoginSignup
1
1

More than 5 years have passed since last update.

Object Spread Operatorを使ってReducerを見やすくする

Last updated at Posted at 2018-09-13

はじめに

最近react-redux書き始めたんですが、Reducerを書いて行く中で、Object.assignを使っていたんですが、少し見にくいなと思っていました。
そこで調べた結果Object Spread Operatorを使うというのがRedux公式にありました。
使って見た結果、Obeject.assignよりも可読性が高いなと思ったので(個人的に)一応Qiitaにまとめておこうと思います。

Object Spread Operator

コード見た方が早いのでコードを見せます。
服の情報を非同期でとってくる処理を書きたい場合にはこんな感じでかけます。(簡略化してます。)
非常にシンプルです。


import * as types from 'client/constants/ActionTypes/Clothes';

const initialState = {
  fetching:   false,
  fetched:    false,
  clothes: [],
}

const Clothes = (state = initialState, action) => {
  switch(action.type){

    case types.FETCH_CLOTHES:
      return {
        ...state,
        fetching: true,
        fetched: false,
      }

    case types.FETCH_CLOTHES_SUCCESS:
      return {
        ...state,
        clothes: {
          ...state.clothes,
          ...action.payload
        },
        fetched: true,
      }

    case types.FETCH_CLOTHES_FAILED:
      return {
        ...state,
        fetching: false,
        fetched: false,
      }

    default:
      return state
  }
}

export default Clothes;

この部分にだけ注目して見ます。


    case types.FETCH_CLOTHES_SUCCESS:
      return {
        ...state,
        clothes: {
          ...state.clothes,
          ...action.payload
        },
        fetched: true,
      }

Obejct.assignを使うとこんな感じ、少し見にくい気がします。


    case types.FETCH_MEDICINES_SUCCESS:
      new_clothes = Object.assign({}, state, action.payload);
      return Object.assign({}, state, clothes: new_clothes, fetched: true);

終わりに

参考になれば幸いです。
よかったらいいね!押していただけると嬉しいです!

ご意見アドバイス等もぜひお願いします!

参考

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1