簡體   English   中英

如何以一種動作將數據傳播到React架構中的許多存儲?

[英]How to spread data with one action to many stores in React flux arcitecture?

如何將一些動作數據發送到許多商店?

例如,我通過用戶操作從服務器獲取了一些發布數據。

因此,這是簡單的偽操作代碼。

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');
    }

    // ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM