0
1

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.

switchを使わずにObjectでReducerを書く

0
Last updated at Posted at 2020-12-23

Reducerをオブジェクト(Object)で作りたい

ReactのフックAPIのリファレンスを見ると、以下のようにswitchを使ってReducerを定義している。
しかし、私はswitchがあまり好きではないので、オブジェクトで書くようにしている。

example.js

const initialState = {count: 0};

function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}

引用: フックAPIリファレンス(https://ja.reactjs.org/docs/hooks-reference.html#usereducer)


# createReducer関数をつくる
以下のようにReducerを書けるようにcreateReducerという関数を作った。

```js
{
    [アクションタイプ1]: (state, action) => ({変更後のステート}),
    [アクションタイプ2]: (state, action) => ({変更後のステート}),
    ...
}
createReducer.js
export const createReducer = (initialState={}, handlers={}) =>
  (state = initialState, action) =>
    handlers[action.type] && handlers[action.type]({...state}, action) || {...state}

説明は割愛するが、これを利用することで、前述のフックAPIリファレンスのサンプルコードを以下のように書くことができる。

example.js
const initialState = {count: 0};

const reducer = createReducer(initialState, {
  ['increment']: state => ({...state, count: state.count + 1}),
  ['decrement']: state => ({...state, count: state.count - 1})
}), initialState)

また、 payloadがある場合には、以下のように書くことができる。

example.js
const reducer = createReducer(initialState, {
  [UPDATE_SUGGESTION_ITEMS]: (state, {payload}) => ({...state, suggestionItems: payload}),
  [FETCH_POSTS]: (state, {payload}) => ({...state, tmpResult: payload}),
  [FETCH_POST_DETAIL]: (state, {payload}) => ({...state, post: payload}),
}), initialState)
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?