React / Redux,chain或promise in reducer

时间:2015-12-29 03:48:22

标签: javascript reactjs redux

我有一个react / redux应用程序,我有一些过滤和搜索。由于API的设置方式,我必须在接收过滤器然后发送新的搜索查询之间做一些基础工作。所以我有一个有效过滤器的小参考图,每次检查或取消选中过滤器时都会更新。问题是,我希望运行更新过滤器的操作,然后在此之后用新的过滤器参数调用服务器的操作,我不确定这个工作流是如何进入redux的。

所以我调用了动作,然后它就像更新状态一样击中了reducer -

 case actions.TOGGLE_FILTER:
            return toggleFilter(state, action);


var toggleFilter = function(state, action){
var currentFilters = state.toJS().activeFilters || {};
var removeFilterFromActive = function(item) {
    if(item != action.filter.search){
        return;
    }
}
//already exists, remove from list (toggle off)
if (currentFilters[action.filterGroup.parentSearch] && currentFilters[action.filterGroup.parentSearch].indexOf(action.filter.search) > -1) {
    var itemIndex = currentFilters[action.filterGroup.parentSearch].indexOf(action.filter.search);
    currentFilters[action.filterGroup.parentSearch].splice(itemIndex, 1);
} else {
    //add to obj
    var newObj = {};
    if (currentFilters[action.filterGroup.parentSearch]) {
        currentFilters[action.filterGroup.parentSearch].push(action.filter.search);
    } else {
        newObj[action.filterGroup.parentSearch] = [];
        newObj[action.filterGroup.parentSearch].push(action.filter.search);
        _.extend(currentFilters, newObj);
    }
}
return state.set('activeFilters', fromJS(currentFilters));
};

所以这组装我的activeFilters状态,现在似乎工作正常。但我无法弄清楚的部分是如何使用我更新的activeFilters调用服务器。现在我只是从它正在使用的组件中调用此动作。

当减速器完成后,有没有办法在减速器内链接,承诺或调度另一个动作?如何处理这个问题的任何建议将非常感激。谢谢!

1 个答案:

答案 0 :(得分:8)

减速器应该是纯净的,没有副作用,因此您不希望减速器向服务器发出请求或发出其他操作。

如果您使用redux-thunk,则可以将功能分派为操作。这些功能可以检查商店的状态。这些函数可以自己发送多个常规动作。而且,如果您没有对Redux更新进行任何类型的批处理,他们可以在发布操作后检查商店,然后执行更多操作。

考虑到上述情况,您可以执行以下操作:

function createToggleFilterAndQueryServerAction(filterGroup, filter) {
    return (dispatch, getState) => {
        // first dispatch the filter toggle
        // if you do not have any batching middleware, this
        // should run the reducers and update the store
        // synchronously
        dispatch(createToggleFilter(filterGroup, filter));

        // Now get the updated filter from the store
        const activeFilter = getState().activeFilter;

        // now query the server
        callServer(activeFilter).then(result => {
            // Now dispatch an action with the result from the server
            dispatch(createServerResponseAction(result));
        });
    };
}

用法:

dispatch(createToggleFilterAndQueryServerAction(..., ...));