LoginSignup
66
47

More than 5 years have passed since last update.

[Redux] Reducerでのstateの更新方法まとめ

Last updated at Posted at 2019-02-04

概要

今回はReducerでのstateの更新方法についてみていきます。
例えば配列のstateに要素を追加したい場合は

const exampleReducer = (state = [], action) => {
  switch (action.type) {
    case 'EXAMPLE_ACTION':
      return [
        ...state,
        action.payload
      ];
    default:
      return state;
  }
};

上記のようなコードになると思います。
state.push(action.payload);のようにしてはいけません。
重要なのは更新の際、新たな配列を作るということです。
じゃあ削除は?入れ替えるのは?オブジェクトの場合は?と疑問になったのでそれらをまとめていきます。

更新方法まとめ

先に配列の更新方法をみていきましょう。以下になります。

種類 bad!! good!!
削除 state.pop() state.filter(el => el !== 'xxx')
追加 state.push('xxx') [...state, 'xxx']
入れ替え state[0] = 'y' state.map(el => el === 'y' ? 'xxx': el)

'xxx'にはそれぞれ削除したいもの、追加したいもの、入れ替えたいものが入ります。
次にオブジェクトの更新方法をみていきましょう。

種類 bad!! good!!
削除 delete state.name {...state, name: undefined}
追加 state.name = 'xxx' {...state, name: 'xxx'}
入れ替え state.age = 10 {...state, age: 10}

オブジェクトの場合、追加と入れ替えは同じような書き方なります。
削除に関してはlodashを使って以下のように書くこともできます。

_.omit(state, 'name')

lodashについてはまだあまり調べきれていないので別途記事にできればと思っています。

まとめ

今回はReducerのstateの更新方法についてまとめました。
参考になれば幸いです。

66
47
0

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
66
47