LoginSignup
5
2

More than 5 years have passed since last update.

Reduxのreducerの実験

Posted at

reducerの作り方が色々な方法があるし、combineReducersだけ使うと、各stateでreducerを分けたときに、その他のstateの情報がとれないので困った。あとObject.assignが増えてコードがごちゃごちゃする。

解決策として、reduceReducerを使ったり、immutable.jsを使ったりするといいと色々なところに書いてあったのでとりあえず試してみた。

src/index.js
import { createStore, combineReducers } from 'redux'
import reduceReducer from 'reduce-reducers'
import { Map, fromJS } from 'immutable'

const hoge = (state = 0, action) => {
  switch (action.type) {
    case 'HOGE':
      return state + parseInt(action.num, 10)
    default:
      return state
  }
}
const moge = (state = 1, action) => {
  switch (action.type) {
    case 'MOGE':
      return state * parseInt(action.num, 10)
    default:
      return state
  }
}
const arra = (state = [], action) => {
  state = fromJS(state)
  switch (action.type) {
    case 'ADD_ARRA':
      return state.push(
        Map({ id: action.id, name: action.name , moge: 0})
      ).toJS()
    case 'EDIT_ARRA':
      let idx = state.findIndex(s => s.get('id') === action.id)
      return state.setIn([idx, 'name'], action.name).toJS()
    default:
      return state.toJS()
  }
}
const arraForMoge = (state, action) => {
  state = fromJS(state)
  switch (action.type) {
    case 'ADD_ARRA':
      return state.setIn(['arra', -1, 'moge'], state.get('moge')).toJS()
    case 'EDIT_ARRA':
      let idx = state.get('arra').findIndex(s => s.get('id') === action.id)
      return state.setIn(['arra', idx, 'moge'], state.get('moge')).toJS()
    default:
      return state.toJS()
  }
}
const redu = combineReducers({ hoge, moge, arra })
const reducer = reduceReducer(redu, arraForMoge);
let store = createStore(reducer)

store.subscribe(() => {
  console.log(store.getState())
})

store.dispatch({type: 'HOGE', num: 3})
store.dispatch({type: 'HOGE', num: 5})
store.dispatch({type: 'MOGE', num: 3})
store.dispatch({type: 'ADD_ARRA', name: 'apple', id: 1})
store.dispatch({type: 'MOGE', num: 2})
store.dispatch({type: 'ADD_ARRA', name: 'orange', id: 2})
store.dispatch({type: 'MOGE', num: 4})
store.dispatch({type: 'EDIT_ARRA', name: 'coffee', id: 1})
store.dispatch({type: 'MOGE', num: 5})
store.dispatch({type: 'ADD_ARRA', name: 'mame', id: 3})

immutable.jsは確かに便利だなーと思った。reduceReducersの使い方は、別のstateが必要なところを残して、全部一回combineReducersしてからreduceReducersを使ってみた。なんか非効率な気がする。もしかしてcombineReducers使わなくてもいいんじゃないかとも思った。でもstate数がめちゃくちゃ増えたときはやっぱりcombineReducersを前提にした方がいいのかなーとも思った。あとは、ここにimmutableを使ってモデルを作ることで効率化できると書いてあるので、それを試してみつつ、大きなstateのコードをgithubとかで探してみてみようかなと思った。

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