减速器中的React/Redux、chain或promise

React/Redux, chain or promise in reducer

本文关键字:chain promise Redux React 减速器      更新时间:2023-09-26

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

所以我调用该操作,然后它会以更新后的状态到达reducer,比如So-

 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调用服务器。现在我只是从正在使用的组件调用此操作。

当这个动作完成后,有没有办法在减速器内连锁、承诺或调度另一个动作?任何关于如何处理这一问题的建议都将不胜感激。谢谢

Reducer应该是纯的,没有副作用,所以你不希望你的Reducer向服务器发出请求或发出额外的操作。

如果您正在使用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(..., ...));