LoginSignup
6
7

More than 5 years have passed since last update.

コードで理解するRedux入門

Last updated at Posted at 2017-09-17

コードで理解するReact入門 の続き

前回までのコード
スクリーンショット 2017-09-17 11.46.37.png

state名をgreetings -> usersに変更。
入力したユーザー名をstate.usersに追加するコードを追加
スクリーンショット 2017-09-17 11.55.53.png

inputに入力した文字列を配列に追加していくシンプルな実装
スクリーンショット 2017-09-17 14.31.39.png

Reduxのためのディレクトリ構成

スクリーンショット 2017-09-17 12.09.37.png

src/
  actions/
  components/
  containers/
  reducers/

を追加

index.jsはディレクトリのデフォルトエクスポートファイルになるので、インポートの際ディレクトリのパスを指定するだけでいい。

必要なライブラリをインストール

redux : reactとは独立していて、React以外のAngularやVueなどでも使える。
react-redux : reactとreduxを連携するために必要(Providerコンポーネント, connect関数)

$ yarn add redux react-redux // or npm install --save redux react-redux

Storeの生成

エントリーポイントであるsrc/index.jsでstoreを生成する。
import App from './components/App'じゃなくて、import App from './containers/App'が正しい

スクリーンショット 2017-09-17 12.35.31.png

Action

stateが決まったら、そのstateに対して考えられるアクションを洗い出す。

ユーザーを追加するアクション
スクリーンショット 2017-09-17 13.48.41.png

Reducer

reducer : 受けたactionのタイプをもとに、storeに新しいstateを渡す

userに関するreducerに
スクリーンショット 2017-09-17 13.48.30.png

複数あるreducerをまとめて、それをstore生成時に渡す。
そうするとstoreのstateがreducerごとにツリー構造になる。(シンプルなstateツリーを心がける)
state.reducer名.プロパティで取得できる。
スクリーンショット 2017-09-17 13.59.13.png

connect関数

Appコンポーネントにstateと関数を渡すためのコンポーネント(ContainerComponent)
スクリーンショット 2017-09-17 13.58.47.png

Presentational Component

state-lessなAppコンポーネント(Presentational Component)
スクリーンショット 2017-09-17 13.51.57.png

おまけ

React-dev-tools

Webコンソールからコンポーネント構造や渡っているオブジェクトなどがわかりやすくなる。

スクリーンショット 2017-09-17 14.32.37.png

6
7
2

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
6
7