LoginSignup
72
45

More than 5 years have passed since last update.

Redux + React + ES6 の簡単アプリを作成する①(Redux編)

Last updated at Posted at 2016-06-17

背景

  • Reactにも慣れが出てきたので、次はFluxのデータフローについて学ぼうと思った。
  • Fluxの詳しいデータフローに関しては、公式サイトや別の記事を参考に。
  • Fluxのフレームワークとしては、頭1つ抜けているReduxを選定した。
  • ReactとReduxの連携部分で多少はまったのでメモ。

687474703a2f2f692e696d6775722e636f6d2f4a65567164514d2e706e67.png

学習内容

  • Flux(Reduxベース)の基本的な考え方。
  • Flux(Reduxベース)のデータフローと登場人物。
  • Fluxでよくみる図。 flux.png

概要

入力した内容がそのまま出力されるだけのアプリ。
state管理をReduxのみで行う。

react-redux.gif

Action

ActionはActionCreatorという純粋な関数である。
ActionCreatorはActionオブジェクトを返し、Store(※後述)のdispatch関数に引数として渡される事でStoreにEmit出来る。

src/actions/FormActions.jsx

const SEND = 'SEND';

export default {
  send(value) {
    return {
      type: SEND,
      value
    };
  }
} ;

ActionCreatorの返り値は、Actionオブジェクトとなり、dispatchの対象となる。
ReducerでどのActionかを判別するために、typeプロパティは必須で指定する。

Reducer

ActionがStoreにdispatchされたら、Reducerが発火。
現在のstateとdispatchされてきたActionを元に新しいstateを発行する。

src/reducers/FormReducer.jsx
const formReducer = (state, action) => {
  switch (action.type) {
    case 'SEND':
      return (
        Object.assign({}, state, {
          value: action.value
        })
      );
    default:
      return state;
  }
};

export default formReducer;

Reducerは複数定義可能な関数であるが、最終的にStoreが作られる際に渡されるReducerは1つだけである。
複数作成したReducerは1つにまとめる必要がある。
Object.assignを使っているのは、ReduxはReducerで引数として渡された現在のstateとの差分を元に新しくstateを作成します。
Reduxの考え方(Fluxの考え方)として、既存のstateを書き換える事はしません。
あくまでも、新規でstateを作成する為に、Object.assignを利用します。

src/reducers/AppReducer.jsx
import formReducer from './FormReducer';

const reducers = formReducer;

export default reducers;

先程作成したFormReducerと、ReduxのcombineReducers関数を呼び出し、複数のReducerを結合する事が可能。
今回は1つのReducerで処理する為、そのままexportしている。
(今回はReducerを複数に分ける必要もありませんが、一応分けます。)

Store

Storeはstateを管理する単純なオブジェクトである。
Reactの様にどこでも宣言できるだけではなく、1つのアプリケーションにつきStoreは1つである。
ReduxのcreateStore関数に、Reducerを渡す事でStoreが作成される。

終わり

Redux自体はAction->Reducer->Storeの単純な流れに過ぎない。
(Reactのstate管理を奪い取るイメージ)
次回はReact+Reduxの連携を試してみる。

72
45
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
72
45