クイックリファレンス

Flux チートシート(単方向データフローアーキテクチャ)

Facebook が提唱した単方向データフロー Flux アーキテクチャのクイックリファレンス。Dispatcher、Action、Store、waitFor、React 統合を整理。

· 公開日

Flux は、Facebook が提唱した、予測可能な単方向データフロー(Unidirectional Data Flow)を持つフロントエンドアプリケーション設計パターンです。

アーキテクチャの概要(Architecture Overview)

  ┌───────────────┐
  │ Action Creator│ ───> Action ───┐
  └───────────────┘                │
                                   ▼
┌───────┐                      ┌────────────┐
│ View  │ <── Change Event ─── │   Store    │ <─── Dispatch(Action)
└───────┘                      └────────────┘
    │                               ▲
    └──────── Action Trigger ───────┘
  • Dispatcher: Central hub receiving actions and broadcasting to registered callbacks.
  • Stores: Maintain state and business logic, updating on action dispatch.
  • Views: React components listening to store changes and triggering actions.

Dispatcher と waitFor による実行順序制御

const { Dispatcher } = require('flux');
const AppDispatcher = new Dispatcher();

// Register a store callback; returns a token used for waitFor()
const token = AppDispatcher.register(function (payload) {
  switch (payload.actionType) {
    case 'TODO_CREATE':
      TodoStore.create(payload.text);
      TodoStore.emitChange();
      break;
  }
});

// Broadcast action payload
AppDispatcher.dispatch({
  actionType: 'TODO_CREATE',
  text: 'Learn Flux'
});
// Sequencing with waitFor()
const FlightStore = {
  dispatcherIndex: AppDispatcher.register(function (payload) {
    switch (payload.actionType) {
      case 'BUY_TICKET':
        AppDispatcher.waitFor([CityStore.dispatcherIndex]);
        FlightStore.country = CityStore.getCountry();
        break;
    }
  })
};

Store の構造と React 画面連携

const EventEmitter = require('events').EventEmitter;

const TodoStore = Object.assign({}, EventEmitter.prototype, {
  _todos: {},
  getAll() { return this._todos; },
  emitChange() { this.emit('change'); },
  addChangeListener(cb) { this.on('change', cb); },
  removeChangeListener(cb) { this.removeListener('change', cb); }
});

TodoStore.dispatchToken = AppDispatcher.register(function (action) {
  switch (action.type) {
    case 'TODO_CREATE':
      TodoStore._todos[Date.now()] = { text: action.text };
      TodoStore.emitChange();
      break;
  }
});

関連するチートシート

関連テーマ