如何在反应Flux App中管理多个api调用

时间:2016-02-25 17:09:34

标签: api reactjs flux

所以我有一个Api,它通过" hourOfDay"

提供报告
http://localhost:8080/api/v1/reports/61?aggregation=hourOfDay&start=2016-02-10T00:00:00.000Z&stop=2016-02-20T10:59:59.000Z

在我的React应用程序中,我想显示此内容和之前的时间范围。这需要对该端点进行另一次调用,以便在图表中进行比较。

http://localhost:8080/api/v1/reports/61?aggregation=hourOfDay&start=2016-02-20T00:00:00.000Z&stop=2016-02-30T10:59:59.000Z

那我该怎么做?

我是否有一个服务 - 动作 - 存储 - 组件组合。就像服务被调用并且它触发两个api调用一样,等待两个并且然后传递给动作而不是商店,所以组件可以同时访问所有数据?或者我将如何解决这个问题?我的意思是我可以更改api端点,但我希望它尽可能干净,我想以后其他地方需要单个报告端点...

2 个答案:

答案 0 :(得分:0)

我更喜欢使用系列。行动 - > Api.get - > Api.onGot - >行动 - >商店 - >行动 - > Api.get - > Api.onGot - >行动 - >存储并刷新。

答案 1 :(得分:0)

我认为更好的方法是View调用一个调用2个API请求的Action。第一个被调用的请求重定向嵌套请求的结果。

请参阅此伪代码:

YourView:

// this function is called when the result2 is dispatched.
// you can get the information from the Store
function receiveResultFromTimeRange () {
    console.log(YourStore.getResult2());
},

// listening for the result2
function componentDidMount () {
    YourStore.addChangeListener(this.receiveResultFromTimeRange);
    YourAction.timeRange(parameter1);
}

YourAction:

return {

    // you can call only the second request in this way
    request2: function(parameter2) {
        new RequestService().secondRequest(result1).done(function (result2) {
            Dispatcher.dispatch({
                method: 'receiveResultFromSecondRequest',
                result: result2
            });
        });
    },

    // call the first request and use the result to call the second request
    request1And2: function(parameter1){
        new RequestService().firstRequest(parameter1).done(function (result1) {
            this.request2(result1);
        });
    }
}

YourStore:

var _result2 = null;

receiveResultFromSecondRequest: function (result2) {
    // save result2 in the Store, LocalStorage... whatever you want.
    _result2 = result2;
    this.emit(SUCCESS_SECOND_REQUEST);
},

addChangeListener: function (callback) {
    this.addListener(SUCCESS_SECOND_REQUEST, callback);
},

getResult2: function(){
    return _result2;
}