javascript - Redux - 在操作或 reducer 中调用函数链?

标签 javascript reactjs redux

我有一个逻辑问题,我是否应该对操作内的每个回调进行多个函数调用:

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/

相关文章:

php - Next js - 每次更改路由时在服务器端调用一个函数

javascript - 如何在 redux 中创建/编辑/删除嵌套结构?

javascript - 无法解构 'chats' 的属性 'this.props.data',因为它未定义

javascript - 从列表中选择随机段落

javascript - 在状态变化时 react 变化类名

reactjs - 使用 graphql react 组件默认 props

javascript - 在reactjs中返回带有更新数组的整个对象

javascript - node jasmine - 如何对涉及 redis 调用的函数进行单元测试?

javascript - 如何在 json 数组中实现搜索

javascript - requirejs 竞争条件 - 如何阻止直到检索到上一个文件