10
10

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.

Reduxのreducerはオブジェクトで書こーず!!

Last updated at Posted at 2016-11-03

オブジェクトでキーマッチすればswitchより全然無駄がないはず。
でもどこを見てもみんなswitchでしか書かれていない。。。
ふ、不安なので、ここは仲間を増やしていこう!

ということで、こちら投稿してみました。
何かswitchで書かいたほうが良い理由などあれば教えてください!

以下、サンプル

import Immutable  from 'immutable';
import * as types from '../const/actionTypes';

// 初期stateの設定
const defaultState = {
    hoge  : false,
    fuga  : true,
    error : false,
};
const initialState = Immutable.Map(defaultState);

// 共通のエラー処理
const setError = (state) => (
    state.set('error', true)
);

// 今までswitchに入っていた処理をオブジェクトに入れたところ
const reducers = {

    [types.SET_HOGE] : (state, action) => (
        state.set('hoge', action.hoge)
    ),

    [types.SET_ALL_FLAG_FALSE] : (state) => (
        state.withMutations(m => (
            m
                .set('hoge', false)
                .set('fuga', false)
        ))
    ),

    [types.RESET] : () => initialState,

    // fall through で書いていたところは一度関数で書いて当てる
    [types.PIYO_ERROR] : setError,
    [types.PICO_ERROR] : setError,

};

// reducer本体
export default (state = initialState, action) => {
    if (reducers[action.type]) {
        return reducers[action.type](state, action);
    }
    return state;
};
10
10
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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?