44
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React&Reduxを牛丼屋に例えてみる図

Last updated at Posted at 2017-02-13

redux.png

redux.png
import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';

// 座席確保(State)
const initialState = {
  // 単品メニューの準備
  menu: '',
  // 全ての注文の準備
  menus: []
}

// チケット販売機(ActionCreator)
const inputCoin = (menu) => (
  {
  // 基本オーダー(Action)
  type: 'WATER',
  payload: {
    menu
  }
});

const addTicket = (menu) => (
  // 食券オーダー(Action)
  {
  type: 'TICKET',
  payload: {
    menu
  }
});

// スタッフが食券を厨房に伝える(store)
const store = createStore(kitchen);

// 厨房(Reducer)
function kitchen (state = initialState, action) {
  // 食券の確認
  switch (action.type) {
    case 'WATER':
      return {
        // 全ての注文
        ...state,
        // 単品メニューを準備
        menu: action.payload.menu
      };
    case 'TICKET':
      return {
        ...state,
        // 単品メニューを今までの注文に追加
        menus: state.menus.concat([action.payload.menu])
      }
    default:
      // チケットがなければ今ままでの注文を返す
      return state;
  }
}

// カウンター(React)
function EatCounter ({ store }) {
  // 単品メニューおよび全ての注文を確認
  const { menu, menus } = store.getState();
  return (
    <div>
      {/* 食券をスタッフが声出し確認(dispatch) */}
      <input type="text" onChange={(e) => store.dispatch(inputCoin(e.target.value))} />
      {/* 食券をスタッフに渡す(dispatch) */}
      <input type="button" value="購入" onClick={() => store.dispatch(addTicket(menu))} />
      <ul>
        {/* カウンターに注文メニューを個別に配置 */}
        {
          menus.map(function(item, i) {
          return (
              <li map={i}>{item}</li>
            );
          })
        }
      </ul>
    </div>
  );
}

// お客さんに商品を渡す
function renderApp (store) {
  render (
    <EatCounter store={store} />,
    document.getElementById("root")
  );
}

// 厨房にチケットが渡された時はカウンターを再確認
store.subscribe(() => renderApp(store));
renderApp(store);
44
27
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
44
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?