100
68

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.

combineReducersでハマったメモ

Last updated at Posted at 2016-02-26

reduxの勉強にとおもって、簡単なカウンターアプリを1から作ってみたんだけれど、
reducerの分割時にcombineReducers()でしばらく悩んだので書き残しておきます。

返却値

まずはreducerが1つの場合

./reducer/counter.js
const initialState = {
    count: 0,
};

function counter(state = initialState, action) {
...
    default:
        return state;
    }
}

export default counter;
./reducer/index.js
import counter from './counter';

export default counter;
./app.js
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import reducer from './reducer';

let store = createStore(reducer);

console.log(store.getState());

render(
    <Provider store={store}>
        <RootComponent />
    </Provider>,
    document.querySelector('#app')
);

この状態で途中に記述してあるconsole.log()の返却値は

Object {
  count: 0
}

次にreducerを分割するために、2つに増やした場合

combineReducers()を使って2つのreducerをガッチャンコしてからexportします。

./reducer/index.js
import {combineReducers} from 'redux';
import counter from './counter';
import counterB from './counterB';

const reducer = combineReducers({
    counter,
    counterB
});

export default reducer;

そうすると、app.js側のconsole.log()の返却値は

Object {
  counter: {
    count: 0
  },
  counterB: {
    countB: 0
  }
}

Objectが一階層ネストされて返却されます。
これを発見するのにしばらく悩みました。

Component側のmapStateToPropsに注意

Component側でstateをひも付けてやる必要があるんですが、その際に

1つの場合はこれでいいんですが、

const mapStateToProps = (state) => {
    return {
        count: state.count
    };
};

combineReducers()を使った場合には、ネストされた分を考慮してやる必要があります。

const mapStateToProps = (state) => {
    return {
        count: state.counter.count
    };
};

オブジェクト構造を蔑ろにして実装を進めていくと、くだらない所でこける気がしたのでご注意を。
あとthisとか特に。

100
68
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
100
68

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?