React with Redux toDoList パート3

Tuyoshi Akiyama
Jul 26, 2017 · 9 min read

前回の記事の続きになります。また、以下の記事を参照して、まとめていきます。


Reduxとは

  • UI要素はアクションを送出(dispach)します。
  • そのアクションは関連情報のみを含むオブジェクトで、アクションはreducerに送信されます。
  • reducerはアプリとアクションの現在のstateを受け取り、新しいstateを返します。
  • 新しいstateはUIを管理し、そのstateが変化したときに合わせて、UIも効率的に更新されます。

submitボタンのアクション

まず、次のファイルを作ります。

src/constants/index.js

const types = {
SUBMIT_TODO: 'SUBMIT_TODO',
};

さらに、アクションのテストを作ります。

src/actions/test.js

/* global expect, it, describe */

定数expectedActionは、submitTodo関数を呼んだ時に、Appから送られるアクションを定義しています。

実際の値とexpectedActionを比較して、期待通りの機能かどうかのテストになります。

このテストを yarn run test で実行して、エラーが出ないようなindexファイルを書いてきます。

src/actions/index.js

import types from '../constants';

submitボタンのreducer

actionからreducerへとstateが渡されて、reducerはそれを管理(store, and return new one)しています。

まず、reducerのテストを書きます。

src/reducers/test.js

/* global expect, it, describe */

src/reducers/index.js

import types from '../constants/';

上の処理では、reducerの第二引数actionがSUBMIT_TODOタイプの時に、何をreturnをしているかが定義されています。

...state は第一引数のstateのコンテンツ全てをreturnしています。

todo: [...state.todos, {id: action.id, text: action.text}]

todo配列をunpackedしたものをreturnし、つまりstateの配列全てを展開して、新しい要素(id, text)を持つオブジェクトを加えます。

よって、todo配列に固有のid,textが代入されます。


Redux

まず、reduxのインスールを行いstoreをつくります。

npm install --save redux react-redux

src/store.jp

import { combineReducers, createStore } from 'redux';
import todoListApp from './reducers';

reducerを一つにまとめる(combineReducers)ことで、全ての state treeの管理を行っています。


次にindexページをrefactorします。

src/index.js

/* global document */

<Provider> は、storeのchild componentsを全てwrapしています。


src/App.js

import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import AddTodo from './components/addTodo/';
import actions from './actions/';

定数mapStateToPropsは、store内にあるstateを、コンポーネントのpropsとして扱えるようにする関数です。

また、定数mapDispatchToPropsはアクションをpropsとして扱えるようにする関数になります。また、textを引数にとるsubmitTodo関数を入れ、action.submitTodoを発信します。

connectモジュールは、アクションをdispatchしてstateをsubscribeすることで、Appコンポーネントとstateとがつながるような役割を持っています。


参考リンク

また、Reduxがどのような流れで処理が行われているのかを、具体例をもって説明された、以下の記事が分かりやすかったです。

Tuyoshi Akiyama

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade