Redux:使用thunk中间件和combineReducers为getState引入了额外的密钥

时间:2016-01-07 22:42:48

标签: javascript redux redux-thunk

问题:在引入thunk之前使用Redux.combineReducers中间件时,传递给thunk的getState会正确返回具有正确密钥的对象。在重构使用Redux.combineReducers之后,传递给thunk的getState现在返回具有嵌套键的对象。请参阅下面的代码(希望)说明我的观点。这可能导致潜在的维护噩梦,即必须不断地为访问状态的任何thunk方法获取正确的密钥。

问题:是否有一种简单的方法可以在thunk中设置正确的上下文密钥?当我组合Reducer并且必须插入密钥以访问正确的状态时,代码会感觉很脆弱。我错过了一些简单的东西吗?

在代码之前:

const Redux = require('redux'),
    Thunk = require('redux-thunk');

// this is an action generator that returns a function and is handled by thunk
const doSomethingWithFoo = function() {
    return function(dispatch, getState) {
        // here we're trying to get state.fooValue
        const fooValue = getState().fooValue;
        dispatch({ type: "DO_SOMETHING", fooValue });
    }
};
// this is a simple action generator that returns a plain action object
const doSimpleAction = function(value) {
    // we simply pass the value to the action. 
    // we don't have to worry about the state's context at all.
    // combineReducers() handles setting the context for us.
    return { type: "SIMPLE_ACTION", value };
}

const fooReducer(state, action) {
    // this code doesn't really matter
    ...
}

const applyMiddleware = Redux.applyMiddleware(Thunk)(Redux.createStore);
const fooStore = applyMiddleware(fooReducer);

在代码之后(引入更全球的appStore):

// need to rewrite my thunk now because getState returns different state shape
const doSomethingWithFoo = function() {
    return function(dispatch, getState) {
        // here we're trying to get state.fooValue, but the shape is different
        const fooValue = getState().foo.fooValue;
        dispatch({ type: "DO_SOMETHING", fooValue });
    }
};


const appReducers = Redux.combineReducers({
    foo: fooReducer,
    bar: barReducer,
});
const appStore = applyMiddleware(appReducers);

2 个答案:

答案 0 :(得分:1)

在考虑了一些之后,我认为答案是重构doSomethingWithFoo动作生成器,以便它接受fooValue作为参数。然后我不必担心状态对象形状的变化。

const doSomethingWithFoo(fooValue) {
    return function(dispatch, getState) {
        // now we don't have to worry about the shape of getState()'s result
        dispatch({ type: "DO_SOMETHING", fooValue });
    }
}

答案 1 :(得分:1)

你过分思考问题。根据定义,store.getState()返回整个状态,combineReducers()将多个子缩减器组合成一个更大的对象。两者都按预期工作。您正在编写自己的应用程序,因此您需要负责实际组织状态并处理它的方式。如果你觉得事情太“脆弱”了,你可以找到一种很好的结构方法,但这不是Redux的问题。

此外,在动作创建者中使用getState()来确定要做什么是一种完全有效的方法。实际上,Redux文档的Reducing Boilerplate部分甚至将其作为演示:

export function addTodo(text) {
  // This form is allowed by Redux Thunk middleware
  // described below in “Async Action Creators” section.
  return function (dispatch, getState) {
    if (getState().todos.length === 3) {
      // Exit early
      return
    }

    dispatch(addTodoWithoutCheck(text))
  }
}