Help us understand the problem. What is going on with this article?

ReactとReduxで複数のReducerを使う

簡単な機能を実装する場合には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も参考に。

y4u0t2a1r0
React, TypeScript, AWS
pa-rk
Webアプリ、スマホアプリの開発を手掛ける技術者集団です。
https://www.pa-rk.co.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away