ajm*_*jma 2 javascript reactjs redux
我有一个react/redux应用程序,我有一些过滤和搜索.由于API的设置方式,我必须在接收过滤器然后发送新的搜索查询之间做一些基础工作.所以我有一个有效过滤器的小参考图,每次检查或取消选中过滤器时都会更新.问题是,我希望运行更新过滤器的操作,然后在此之后用新的过滤器参数调用服务器的操作,我不确定这个工作流程是如何进入redux的.
所以我调用了动作,然后它以更新的状态命中减速器,如此 -
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));
};
Run Code Online (Sandbox Code Playgroud)
所以这组装我的activeFilters状态,现在似乎工作正常.但我无法弄清楚的部分是如何使用我更新的activeFilters调用服务器.现在我只是从它正在使用的组件中调用此操作.
有没有办法在减速器完成时链接,承诺或派遣另一个动作?如何处理这个问题的任何建议将非常感激.谢谢!
减速器应该是纯净的,没有副作用,因此您不希望减速器向服务器发送请求或发出其他操作.
如果您正在使用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));
});
};
}
Run Code Online (Sandbox Code Playgroud)
用法:
dispatch(createToggleFilterAndQueryServerAction(..., ...));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3466 次 |
| 最近记录: |