如何在React通量结构中通过一个操作将数据传播到多个存储



如何将一些操作数据保存到多个存储?

例如,我在用户操作中从服务器获得了一些帖子数据。

这是一个简单的psudo操作代码。

class UserActions {
    getPosts() {
        asyncFetch(apiEndPoint, function(data) {
            /*
             * data : {
             *    PostStore : [ ... ],
             *    UserStore : { ... },
             *    CommentStore : [ ... ],
             *    AppDataStore : { ... },
             *    StatusDataStore : { ... },
             *    ...
             * }
             *
             */
             PostActions.receiveStoreData(data.PostStore);
             UserActions.receiveStoreData(data.UserStore);
             CommentActions.receiveStoreData(data.CommentStore);
             AppDataActions.receiveStoreData(data.AppDataStore);
             StatusActions.receiveStoreData(data.StatusDataStore);
             ...
        }
    }
}

我很好奇在每个调用动作的存储中设置许多存储数据。

如何使用最佳实践进行修复?

您的操作创建者应该使用调度器来调度相应的操作,如下所示:

import { Dispatcher } from 'flux';
class UserActions {
    getPosts() {
        asyncFetch(apiEndPoint, function(data) {
            const action = {
                type: 'ADD_POSTS',
                data
            };
            Dispatcher.dispatch(action);
        }
    }
    // ...
}

然后,一个或多个存储可以向调度器注册并侦听相同的ADD_POSTS操作:

import { EventEmitter } from 'events';
let posts = [];
const PostStore = Object.assign({}, EventEmitter.prototype, {
    dispatcherIndex: AppDispatcher.register(action => {
        const { type, data } = action;
        switch (type) {
            case 'ADD_POSTS':
                posts = posts.concat(data);
                PostStore.emitChange();
            break;
            // ...
        }
        return true;
    });
    emitChange() {
        this.emit('change');
    }
    // ...
});

相关内容

最新更新