1
0

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 3 years have passed since last update.

Reactアプリ内でのReduxの複数のReducerを一つにまとめる方法

Last updated at Posted at 2021-01-23

1. combineReducers()reduxからimportする。

src/reducers/index.js
import { combineReducers } from 'redux';

2. まとめたい他のreducerもimportする。

src/reducers/index.js
import { combineReducers } from 'redux';
import counterReducer from './counter'; // 追加
import loggedReducer from './isLogging'; // 追加

3. importしたcombineReducers()を使用してreducerをまとめる。そしてexport。

src/reducers/index.js
import { combineReducers } from 'redux';
import counterReducer from './counter';
import loggedReducer from './isLogging';

// coombine()を使ってreducerをまとめる。
const rootReducers = combineReducers({
  // key名はなんでも。任意のものでいい。
  counter: counterReducer,
  isLoggedIn: loggedReducer
  // ちなみに、ES6のプロパティ名のショートハンドを使用して以下のようにも書ける
  // counterReducer,
  // loggedReducer
});

export default rootReducers;

4. exportしたrootReducerをsrc/index.jsでimportする。

src/index.js
import roorReducers from './reducers' // ファイル名の指定がない場合、webpackがindex.jsを自動的に指定してくれる

// ReduxのcreateStore()の引数にrootReducersを渡す。
const store = createStore(
  rootReducers
);

完了!

参考

Redux For Beginners | React Redux Tutorial - YouTube
ちょっと高度なJavaScriptの話 - Qiita

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?