5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactとReduxで複数のReducerを使う

Last updated at Posted at 2019-12-04

簡単な機能を実装する場合にはreducerは一つだけでも問題はないですが、
機能が増えるとreducerをモノリスにしておくわけにもいかなくなります。

複数のreducerを機能別に分けて使うにはreduxのCombineReducersを使う方法があります。
使い方のまとめとして投稿します。

CombineReducersのインポート例

rootReducerにreducerを注ぎ込む。
このrootReducerの部分はuseSelectorで取得することができるstateになる。

index.ts
import { combineReducers } from 'redux'
import {
  FirstReducer,
  SecondReducer,
} from './reducer'

const rootReducer = combineReducers({
  first: FirstReducer,
  second: SecondReducer,
})

export default rootReducer

各reducerの例

actionのpayloadは対象のreducerが担当するstateの分だけ用意すれば良い。
CombineReducersがそれらを結合してくれる。

reducer.ts
const initialFirst = {
  hoge: '',
  foo: '',
}
const initialSecond = {
  bar: '',
  baz: '',
}

export const FirstReducer = (
  state: typeof initialFirst,
  action: {
    type: string,
    payload: typeof initialFirst
  }
): typeof initialFirst => {
  switch(action.type) {
    case 'HOGE':
      return {
        ...action.payload,
        hoge: action.payload,
      }
    case 'FOO':
      return {
        ...action.payload,
        foo: action.payload,
      }
    default:
      return state
  }
}

export const SecondReducer = (
  state: typeof initialSecond,
  action: {
    type: string,
    payload: typeof initialSecond
  }
): typeof initialSecond => {
  switch(action.type) {
    case 'BAR':
      return {
        ...action.payload,
        bar: action.payload,
      }
    case 'BAZ':
      return {
        ...action.payload,
        baz: action.payload,
      }
    default:
      return state
  }
}

combineReducers · Reduxも参考に。

5
8
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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?