我有一个逻辑问题,我是否应该对操作内的每个回调进行多个函数调用:
export const myAction= () => (distaptch, getState) => {
callFunctionA(function(e){
if(e){
dispatch(eventA(e));
callFunctionB(function(e){
dispatch(eventB(e));
callFunctionC(function(e){
dispatch(eventC(e));
});
});
}
});
}
或者我可能想将这些调用移至 redux reducer 并从那里调用下一个函数?
const reducer = (state={}, action) => {
switch (action.type) {
case 'EVENT_A':
callFunctionB(action.e);
return state;
case 'EVENT_B':
callFunctionC(action.e);
return state;
default:
return state
}
}
第二种方法在我看来就像反模式,会导致意大利面条式代码......也许我错了?
最佳答案
您假设 reducer 中的分派(dispatch)操作是反模式是正确的。原因非常简洁地提到了in this post .
来自 Redux 文档:
Things you should never do inside a reducer:
Mutate its arguments;
Perform side effects like API calls and routing transitions;
(Call non-pure functions, e.g. Date.now() or Math.random().
[...] For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.
您可以查看Redux-Saga处理异步流,以避免第一个示例中显示的操作的回调 hell 。
关于javascript - Redux - 在操作或 reducer 中调用函数链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42911875/