【发布时间】:2016-04-12 12:24:19
【问题描述】:
问题:在引入Redux.combineReducers 之前使用thunk 中间件时,传递给thunk 的getState 正确返回具有正确键的对象。重构为使用Redux.combineReducers 后,传递给thunk 的getState 现在返回一个带有嵌套键的对象。请参阅下面的代码(希望)说明我的观点。这可能导致潜在的维护噩梦,即必须不断为任何访问状态的thunk 方法获取正确的密钥。
问题:有没有一种简单的方法可以在thunk 中设置正确的上下文键?当我结合减速器并且必须插入键来访问正确的状态时,代码感觉很脆弱。我错过了一些简单的东西吗?
代码前:
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);
代码之后(引入更全球化的应用商店):
// 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);
【问题讨论】:
-
我不认为这与 thunk 中间件有任何关系。它只是拥有多个减速器然后使用
combinerReducers的副产品。doSomethingWithFoo到底是什么?它是一个动作还是组件的一部分? -
您可以看到in the combineReducers function 它期望将先前的状态附加到提供的键上。
-
是的,
thunk中间件不会对密钥进行任何修改。传递给我的操作返回的函数的getState只会天真地返回任何状态。在after版本中,它现在具有嵌套键。该问题特定于使用thunk中间件。我的问题是,在thunk中维护getState上下文将成为一场噩梦,因为您必须不断更新密钥。我将尝试编辑帖子以使其更清晰。 -
我了解您的问题。但是,我也想知道在 thunk 上使用
getState是否会因此被视为反模式(还要记住,动作调度程序上的读取状态有点可疑)。 -
@E_net4:是的,你是对的。我认为答案是重构。
标签: javascript redux redux-thunk