LoginSignup
14
18

More than 5 years have passed since last update.

個人的React周りベストプラクティス⑤ - Reduxディレクトリ構成編

Last updated at Posted at 2017-10-30

前の記事

前回:個人的React周りベストプラクティス④ - Lamdaパッケージ編
一番始め:個人的React周りベストプラクティス① - 構成編

ディレクトリ構成

src
├ actions
│   ├ hogeHoge.js             hogeHogeのcreateAction
│   └ fugaFuga.js             fugaFugaのcreateAction
│
├ components
│   ├ App                     グローバルメニューを表示したり、ルーティングを設定したりするファイルが入ったディレクトリ
│   │  └ App.js
│   ├ HogeHoge
│   │  ├ HogeHoge.js          hogeHogeのPresentaionalのルートコンポーネント(1ページにつき1つ)
│   │  └ HogeHogeContainer.js hogeHogeのContainer Component(1ページにつき1つ)
│   └ FugaFuga
│      ├ FugaFuga.js          fugaFugaのPresentaionalのルートコンポーネント(1ページにつき1つ)
│      └ FugaFugaContainer.js fugaFugaのContainer Component(1ページにつき1つ)
│
├ constants
│   ├ common.js               共通で使う定数
│   ├ hogeHoge.js             hogeHogeでのみ使う定数
│   └ fugaFuga.js             fugaFugaでのみ使う定数
│
├ css
│   ├ common.css              共通で使うCSS
│   ├ hogeHoge.css            hogeHogeでのみ使うCSS
│   ├ fugaFuga.css            fugaFugaでのみ使うCSS
│   └ reset.css               リセットCSS
│
├ lib                         ライブラリディレクトリ
│
├ reducers
│   ├ index.js                すべてのReducerをcombineReducersで1つのReducerにまとめるファイル
│   ├ hogeHoge.js             hogeHogeのReducer
│   └ fugaFuga.js             fugaFugaのReducer
│
└ index.js

簡略図

Reducer、createAction、コンポーネントはドメイン毎にわける

1ページに付き1つのContainer Componentが存在し、1つのPresentaional Componentと紐づく
その下はツリー構造で作る
image.png

Container ComponentとPresentaional Component

JSXを書くのはPresentaional Component、createActionとPresentaional Componentの橋渡しをするのがContainer Componentである。
そのため、Container ComponentにJSXは書かない。

また、bindActionCreatorsを使用しているため、createActionを増やす度にContainer Componentを修正する必要がなく、一度ファイルを作ってしまえば変更することはない。

Container_Componentの例(どのファイルもほぼ同じ import部分とstateの中身のみ変えてコピペ)
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import Component from './HogeHoge';
import * as Actions from './../../actions/hogeHoge';


const mapStateToProps = (state) => (state.HogeHoge);

const mapDispatchToProps = (dispatch) => (bindActionCreators(Actions, dispatch));


const Container = connect(
  mapStateToProps,
  mapDispatchToProps,
)(Component);

export default Container;

次の記事

個人的React周りベストプラクティス⑥ - 開発編

14
18
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
14
18