Learn プログ

-マナビメモ-

Riot.js Redux Rails 2 / 8 「Reduxを使ってtitleを表示させる」

はじめに

フロントにRiot.jsとReduxを使いサーバーサイドにRailsを使い、初めに環境構築し、次にReduxの使い方の流れをみて、最終的に簡単なTodoAppを作成する。

環境構築

簡単な例でReduxの流れをみる

Todo Appの作成

最終的に完成したTodo App
https://github.com/atfeo/Riot_Redux_Rails

参考

Reduxを使ってtitleを表示させる

Reducer

まずindex.jsに

// ./client/src/index.js
function reducer(state, action) {
  return state;
}

を追加しreducerを作成。reducerはactionを受けてstateを変更するメソッド。
reducerのstateにデフォルトの値を設定。

// ./client/src/index.js
function reducer(state = { title: 'Default title' }, action) {
  return state;
}

Store

次にindex.jsに

// ./client/src/index.js
import { createStore } from 'redux';

const reduxStore = createStore(reducer);

を追加しreduxStoreオブジェクトを作成。(オブジェクトで合っているかわからない。)

tagにStoreを渡す

作成したreduxStoreオブジェクトをstoreという名前でtagに渡す。

// ./client/src/index.js
document.addEventListener('DOMContentLoaded', () => {
  riot.mount('sample-output', { store: reduxStore });
});
tagに渡されたStoreからtitleを取り出す

sample-outputタグを次のように書き換える。

<!-- ./client/tags/sample-output.tag -->
<sample-output>
  <h1>{this.opts.store.getState().title}</h1>
</sample-output>

this.opts.storeでreduxStoreオブジェクトにアクセス。
reduxStoreオブジェクトの持つgetState()というメソッドでreducerで定義したstateにアクセスできる。
stateには{ title: 'Default title' }という値が設定されているのでlocalhost:5000を更新するとHello Riot Redux RailsからDefault title に表示が変わる。

Riot.js Redux Rails 3 / 8に続く