Flux详解

219 阅读2分钟

Flux 是 Facebook 用于构建客户端 Web 应用程序的架构,利用单向数据流来补充 React 的可组合视图组件,它更像是一种模式,而不是一个正式的框架,可以理解它与MVC、MVVM是一类东西。

一个Flux应用包含四个部分

Dispatcher: 处理动作分发;

Store: 负责存储数据同时还要接受 Dispatcher派发的动作,根据动作来决定是否要更新应用状态;

Action: 用来描述一个动作,类似于Event

View: 视图部分,负责显示用户界面。

Dispatcher

Flux 提供了Dispatcher 类,用于创建 Dispatcher,理论上一个项目只需一个 Dispatcher 实例就够了,Dispatcher类上挂载的方法如下:

register

用于注册Store中的reduce函数

unregister

解除注册

dispatch

用于派发事件

dispatch(payload: TPayload): void 
import {Dispatcher} from 'flux';

const AppDispatcher = new Dispatcher();

AppDispatcher.dispatch({
  type: ActionTypes.INCREMENT,
  counterCaption: counterCaption
});

Actions

Actions是一系列方法,调用 Dispatcher 派发事件,要定义Action,首先需要需要定义ActionTypes,作为Action的唯一标识

export const INCREMENT = 'increment';

export const DECREMENT = 'decrement';

// 也可以是这样
const ActionTypes = {
  INCREMENT = 'increment',
  DECREMENT = 'decrement'
};
export const actions = {
   increment (counterCaption) {
      AppDispatcher.dispatch({
        type: ActionTypes.INCREMENT,
        counterCaption: counterCaption
      });
   },

   decrement(counterCaption) {
      AppDispatcher.dispatch({
        type: ActionTypes.DECREMENT,
        counterCaption: counterCaption
      });
   };
}

Store

Store中包含应用程序的 State ,Flux 提供了一个基类 FluxReduceStore ,所有的store必须继承这个基类,并实现一个 reduce方法, reduce的函数签名如下:

reduce(state: TState, action: Object): TState

在FluxReduceStore的构造函数中,会调用Dispatcher的register,将Store的回调函数(调用reduce)注册到dispatcher中,Dispatcher中会存储每个Store 的 回调函数,内部有一个存储回调的注册表。

class CounterStore extends FluxReduceStore<number> {
  reduce(state: number, action: Object): number {
    switch(action.type) {
      case:  ActionTypes.INCREMENT:
        return state + action.counterCaption;
      case:  ActionTypes.DECREMENT:
        return state - action.counterCaption;
      default:
        return state;
    }
  }
}

FluxReduceStore中提供getState用于获取当前Store中的状态值,用于在View中渲染,按钮点击后数字 +1,可直接调用actions中的方法

<button onClick="onClickIncrementButton">加1</button>
<button onClick="onClickDecrementButton">减1</button>
<span>{{counter.getState()}}</span>
onClickIncrementButton() {
	actions.increment(1);
}

onClickDecrementButton() {
	actions.decrement(1);
}

当触发Action的dispatch后,内部会遍历Dispatcher中存储的 storeReduce[],并依次调用。

单向数据流

image.png

Flux 应用程序中的数据沿单一方向流动,在Flux的理念里,界面渲染需要依赖Store中的状态,或者状态的映射,如果要改变界面,必须改变Store中的状态,要改变Store中的状态,必须派发一个action,这就是 单向数据流 规矩。在这个规矩之 下,想要追溯一个应用的逻辑就变得非常容易。