Skip to content

Instantly share code, notes, and snippets.

@azu
Last active August 8, 2018 17:31
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save azu/e0274b703ef97226b0db to your computer and use it in GitHub Desktop.
Save azu/e0274b703ef97226b0db to your computer and use it in GitHub Desktop.
flux-utilsについて

flux-utils

facebook/flux 2.0.32.1.0で追加されたflux/utilsについて

see also 2015-08-17のJS: redux 1.0.0、flux-utils、Firefox 40 - JSer.info

はてなブックマーク検索を作りながらFlux Utilsについて学ぶ | Web Scratchにもっと具体的な解説を書きました


flux-utils


flux-utilsの中身

  • Store
    • Base Class
  • ReduceStore
  • MapStore
  • Container

  • MapStore extends ReduceStore extends Store
  • ReduceSTtore
  • MapStore
    • Stateをimmutable mapとして扱う
    • Immutable.jsに依存している

Container

  • mixinsの代わり
  • 一番上のReact ComponentラップするContainerのComponent
    • const container = Container.create(CounterContainer);
    • FluxStoreGroupというのが中にいる
  • Storeを登録しておいて、Storeの変更を元にViewへ通知する

import {Component} from 'react';
import {Container} from 'flux/utils';

class CounterContainer extends Component {
  static getStores() {
    return [CounterStore];
  }

  static calculateState(prevState) {
    return {
      counter: CounterStore.getState(),
    };
  }

  render() {
    return <CounterUI counter={this.state.counter} />;
  }
}

const container = Container.create(CounterContainer);

FluxStoreGroup

  • それぞれのStoreからdispatcherを取り出して通知をまとめる

ファイルサイズ

Before

before

After

after


gif


ファイルサイズ

  • デフォルトのdistにはutils.jsは含まれてないの12KB程度
  • MapStoreを使うとImmutable.jsが入るので200KB弱程度
    • どちらも圧縮せずの場合


シングルトン

// Export a singleton instance of the store, could do this some other way if
// you want to avoid singletons.
const instance = new TodoStore(TodoDispatcher);
export default instance;

Dispatcher

import type {Action} from './TodoActions';

import {Dispatcher} from 'flux';

const instance: Dispatcher<Action> = new Dispatcher();
export default instance;

// So we can conveniently do, `import {dispatch} from './TodoDispatcher';`
export const dispatch = instance.dispatch.bind(instance);

ActionCreator?

  • ActionCreator自体はなくてもよい
  • Action == payloadオブジェクト
  • dispatchで直接Actionを投げてる
dispatch({
    type: 'todo/complete',
    id: todo.id,
});

Store

  • ReduceStoreでstateを持つ
  • stateの変更がFluxStoreGroup経由で通知される
  • => Viewのアップデート

View

  • React Component + Container

まとめ

  • FBJSfacebook/emitterImmutable.jsを使ってる
  • なぜ? => Flowで書くため
    • TypeScriptで書くのにd.tsが必要なようにFlowTypeで書くために自分でライブラリを作ってる

類似研究:

@sairion
Copy link

sairion commented Aug 17, 2015

Thanks for まとめ! 👍

@khirayama
Copy link

とてもわかりやすい。感謝

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment