빠른 참조

Flux 아키텍처 치트시트 (단방향 데이터 흐름)

Facebook이 제안한 단방향 데이터 흐름 Flux 아키텍처 핵심 치트시트. Dispatcher, Actions, Stores, waitFor 순서 제어 및 React 연동을 정리합니다.

· 게시일

Flux는 단방향 데이터 흐름을 통해 예측 가능한 상태 관리를 제공하기 위해 Facebook이 설계한 프론트엔드 애플리케이션 아키텍처 패턴입니다.

아키텍처 개요 (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;
  }
});

관련 치트시트

관련 주제