减速器中的React/Redux、chain或promise
React/Redux, chain or promise in reducer
我有一个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(..., ...));
相关文章:
- 使用promise和mongoose对文档进行排序
- 测试Angular Service解决错误回调中的promise
- 节点协同与生成器和Promise并行流量控制
- 根据是否解析了 Promise 从函数返回值
- 将一个方法转换为promise:Nodejs
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- js promise没有正确关闭
- Angularjs使用“;这个“;promise内的关键字回调
- AngularJS和promise值在调用本地函数时的效果-未定义
- 在ES6 Promise中,我应该在解决/拒绝之前使用return吗
- 以同步方式获取Javascript Promise的值
- NodeJS和pg promise,捕获PostgreSQL异常
- AngularJS使用http进行promise处理
- Angular promise return"未定义的“;值.NET MVC
- Promise/A+ with chain then() 回调用例
- 减速器中的React/Redux、chain或promise
- Ending a Promise chain
- AngularJS : Seqential Promise chain
- Angularjs: chain promises返回一个promise而不是一个对象
- 在promise-chain中传递引用函数的值