React数据流

动机

在学习React的过程中,发现只有修改state这个变量上的数组,其数据显示就会自动改变,那么为什么会这样呢?其实这是一种数据流,也可以看出一种模式。

flux单向数据流

Flux is an application architecture for building complex user interfaces. It eschews MVC in favor of unidirectional data flow. What this means is that data enters through a single place (your actions) and then flow outward through their state manager (the store) and finally onto the view. The view can then restart the flow by calling other actions in response to user input.

在经典的Flux架构里面,一般包括下面几个部分:

  • Dispatcher 处理动作分发,维护 Store 之间的依赖关系
  • Stores 数据和逻辑部分
  • Views 作为视图,同时响应用户交互
  • Actions 用户产生的动作

    图片来源

    在上文中,我们可以看到,其数据流向:用户Action-> Storage -> View.(DispatcherAction 派发到 Store)其数据流是单向的。它跟MVC架构是同一类东西,但是更加简单和清晰.

    举个例子:一个APP可以修改主题(例如Google Materail Design就可以改变主题呀),那么当我们选择主题后(这就是一个Action),APP会存储你要修改的主题信息,然后会更新View。在ALT我们会看到这个过程:

    1.改变主题

changeTheme = (theme) => {
       AppActions.updateTheme(theme);
};

AppAction声明如下:

// #AppActions.js

class AppActions {
    // 真正的修改主题的代码,也就是View层。
    static updateTheme(name) {
        StatusBarAndroid.setHexColor(COLOR[`${name}700`].color);
        return name;
    }

}

export default alt.createActions(AppActions);

2.存储主题信息,在下面代码中,可以看到handleUpdateTheme是修改主题的方法,然后我们将这个方法注册:即this.bindListeners({handleUpdateTheme: AppActions.UPDATE_THEME});

这样在上面调用AppActions.updateTheme就会调用handleUpdateTheme.(所以bindListeners我们可以将其看成是Dispatcher.)

_loadTheme可以看做是一个初始化方法

 // #AppStore.js

 /** * 可以看作表名 */
const THEME = '@Storage:theme';

/** * AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system that is global to the app. * */
class AppStore {

    constructor() {
        this._loadTheme();
        /** * Bind our action handlers to our actions. * 采用大写,并且有下滑线 */
        this.bindListeners({handleUpdateTheme: AppActions.UPDATE_THEME});
    }

    /** * Fetches an item for a key and invokes a callback upon completion. Returns a Promise object. * [callback] : Function that will be called with a result if found or any error. * Promise对象是一个异步的结果,then表示成功之后的结果(类似与Java的Callable与Future) */
    _loadTheme = () => {
        AsyncStorage.getItem(THEME).then((value) => {
            /* * 小技巧: * value || 'paperTeal' * value == null 返回 'paperTeal' * value != null 返回 value */
            this.theme = value || 'paperTeal';
            AppActions.updateTheme(this.theme);
            SplashScreen.hide();
        });
    };

    /** * Sets the value for a key and invokes a callback upon completion. Returns a Promise object. * 该方法在构造函数里面被注册,在用户修改主题的时候被调用. */
    handleUpdateTheme(name) {
        this.theme = name;
        AsyncStorage.setItem(THEME, name);
    }

}

export default alt.createStore(AppStore, 'AppStore');
 // # alt.js

import Alt from 'alt';
export default new Alt();

3.更新View

    // # Toolbar.js
    /*
     * 当Store变化时,更新View.
     */
    componentDidMount = () => {
        AppStore.listen(this.handleAppStore);
    };

    componentWillUnmount() {
        AppStore.unlisten(this.handleAppStore);
    }

    handleAppStore = (store) => {
        this.setState({title: store.routeName, theme: store.theme});
    };

可以看出,AppStore.listen()可以监听Storage的变化,从而更新View

这样就是整个Flux的流程,可以参考这里

React + Flux

那么在React这个框架里面是怎么实现单向数据流的呢?

  • React利用props来传播单向不可改变的数据流,而通过state来传播可以改变的数据流。用户产生一个Action之后,React会根据Dispatcher 来分配每个Action,将其传递给Store,这时要在Store注册onChange函数,通过改变state最终来修改view.

AsyncStorage

顺便说一下,在React用到了这个数据存储系统。还是比较简单的。

AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system that is global to the app.

//存储数据
AsyncStorage.setItem(THEME, name); 
//读取数据.
AsyncStorage.getItem(THEME).then((value) => { /* * 小技巧: * value || 'paperTeal' * value == null 返回 'paperTeal' * value != null 返回 value */ this.theme = value || 'paperTeal'; .... });

上述then我们可以这样理解:

Fetches an item for a key and invokes a callback upon completion. Returns a Promise object.

[callback] : Function that will be called with a result if found or any error.

Promise对象是一个异步的结果,then表示成功之后的结果(类似与Java的CallableFuture)

联系我

本人软件工程大三本科生,若是有错误,请赐教。
QQ: 1906362072

Mail : [email protected]

你可能感兴趣的:(React-Flux)